Path: blob/jdk8u272-b10-aarch32-20201026/hotspot/src/share/vm/opto/callnode.cpp
83404 views
/*1* Copyright (c) 1997, 2015, 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 "compiler/compileLog.hpp"26#include "ci/bcEscapeAnalyzer.hpp"27#include "compiler/oopMap.hpp"28#include "opto/callGenerator.hpp"29#include "opto/callnode.hpp"30#include "opto/escape.hpp"31#include "opto/locknode.hpp"32#include "opto/machnode.hpp"33#include "opto/matcher.hpp"34#include "opto/parse.hpp"35#include "opto/regalloc.hpp"36#include "opto/regmask.hpp"37#include "opto/rootnode.hpp"38#include "opto/runtime.hpp"3940// Portions of code courtesy of Clifford Click4142// Optimization - Graph Style4344//=============================================================================45uint StartNode::size_of() const { return sizeof(*this); }46uint StartNode::cmp( const Node &n ) const47{ return _domain == ((StartNode&)n)._domain; }48const Type *StartNode::bottom_type() const { return _domain; }49const Type *StartNode::Value(PhaseTransform *phase) const { return _domain; }50#ifndef PRODUCT51void StartNode::dump_spec(outputStream *st) const { st->print(" #"); _domain->dump_on(st);}52#endif5354//------------------------------Ideal------------------------------------------55Node *StartNode::Ideal(PhaseGVN *phase, bool can_reshape){56return remove_dead_region(phase, can_reshape) ? this : NULL;57}5859//------------------------------calling_convention-----------------------------60void StartNode::calling_convention( BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt ) const {61Matcher::calling_convention( sig_bt, parm_regs, argcnt, false );62}6364//------------------------------Registers--------------------------------------65const RegMask &StartNode::in_RegMask(uint) const {66return RegMask::Empty;67}6869//------------------------------match------------------------------------------70// Construct projections for incoming parameters, and their RegMask info71Node *StartNode::match( const ProjNode *proj, const Matcher *match ) {72switch (proj->_con) {73case TypeFunc::Control:74case TypeFunc::I_O:75case TypeFunc::Memory:76return new (match->C) MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);77case TypeFunc::FramePtr:78return new (match->C) MachProjNode(this,proj->_con,Matcher::c_frame_ptr_mask, Op_RegP);79case TypeFunc::ReturnAdr:80return new (match->C) MachProjNode(this,proj->_con,match->_return_addr_mask,Op_RegP);81case TypeFunc::Parms:82default: {83uint parm_num = proj->_con - TypeFunc::Parms;84const Type *t = _domain->field_at(proj->_con);85if (t->base() == Type::Half) // 2nd half of Longs and Doubles86return new (match->C) ConNode(Type::TOP);87uint ideal_reg = t->ideal_reg();88RegMask &rm = match->_calling_convention_mask[parm_num];89return new (match->C) MachProjNode(this,proj->_con,rm,ideal_reg);90}91}92return NULL;93}9495//------------------------------StartOSRNode----------------------------------96// The method start node for an on stack replacement adapter9798//------------------------------osr_domain-----------------------------99const TypeTuple *StartOSRNode::osr_domain() {100const Type **fields = TypeTuple::fields(2);101fields[TypeFunc::Parms+0] = TypeRawPtr::BOTTOM; // address of osr buffer102103return TypeTuple::make(TypeFunc::Parms+1, fields);104}105106//=============================================================================107const char * const ParmNode::names[TypeFunc::Parms+1] = {108"Control", "I_O", "Memory", "FramePtr", "ReturnAdr", "Parms"109};110111#ifndef PRODUCT112void ParmNode::dump_spec(outputStream *st) const {113if( _con < TypeFunc::Parms ) {114st->print("%s", names[_con]);115} else {116st->print("Parm%d: ",_con-TypeFunc::Parms);117// Verbose and WizardMode dump bottom_type for all nodes118if( !Verbose && !WizardMode ) bottom_type()->dump_on(st);119}120}121#endif122123uint ParmNode::ideal_reg() const {124switch( _con ) {125case TypeFunc::Control : // fall through126case TypeFunc::I_O : // fall through127case TypeFunc::Memory : return 0;128case TypeFunc::FramePtr : // fall through129case TypeFunc::ReturnAdr: return Op_RegP;130default : assert( _con > TypeFunc::Parms, "" );131// fall through132case TypeFunc::Parms : {133// Type of argument being passed134const Type *t = in(0)->as_Start()->_domain->field_at(_con);135return t->ideal_reg();136}137}138ShouldNotReachHere();139return 0;140}141142//=============================================================================143ReturnNode::ReturnNode(uint edges, Node *cntrl, Node *i_o, Node *memory, Node *frameptr, Node *retadr ) : Node(edges) {144init_req(TypeFunc::Control,cntrl);145init_req(TypeFunc::I_O,i_o);146init_req(TypeFunc::Memory,memory);147init_req(TypeFunc::FramePtr,frameptr);148init_req(TypeFunc::ReturnAdr,retadr);149}150151Node *ReturnNode::Ideal(PhaseGVN *phase, bool can_reshape){152return remove_dead_region(phase, can_reshape) ? this : NULL;153}154155const Type *ReturnNode::Value( PhaseTransform *phase ) const {156return ( phase->type(in(TypeFunc::Control)) == Type::TOP)157? Type::TOP158: Type::BOTTOM;159}160161// Do we Match on this edge index or not? No edges on return nodes162uint ReturnNode::match_edge(uint idx) const {163return 0;164}165166167#ifndef PRODUCT168void ReturnNode::dump_req(outputStream *st) const {169// Dump the required inputs, enclosed in '(' and ')'170uint i; // Exit value of loop171for (i = 0; i < req(); i++) { // For all required inputs172if (i == TypeFunc::Parms) st->print("returns");173if (in(i)) st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);174else st->print("_ ");175}176}177#endif178179//=============================================================================180RethrowNode::RethrowNode(181Node* cntrl,182Node* i_o,183Node* memory,184Node* frameptr,185Node* ret_adr,186Node* exception187) : Node(TypeFunc::Parms + 1) {188init_req(TypeFunc::Control , cntrl );189init_req(TypeFunc::I_O , i_o );190init_req(TypeFunc::Memory , memory );191init_req(TypeFunc::FramePtr , frameptr );192init_req(TypeFunc::ReturnAdr, ret_adr);193init_req(TypeFunc::Parms , exception);194}195196Node *RethrowNode::Ideal(PhaseGVN *phase, bool can_reshape){197return remove_dead_region(phase, can_reshape) ? this : NULL;198}199200const Type *RethrowNode::Value( PhaseTransform *phase ) const {201return (phase->type(in(TypeFunc::Control)) == Type::TOP)202? Type::TOP203: Type::BOTTOM;204}205206uint RethrowNode::match_edge(uint idx) const {207return 0;208}209210#ifndef PRODUCT211void RethrowNode::dump_req(outputStream *st) const {212// Dump the required inputs, enclosed in '(' and ')'213uint i; // Exit value of loop214for (i = 0; i < req(); i++) { // For all required inputs215if (i == TypeFunc::Parms) st->print("exception");216if (in(i)) st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);217else st->print("_ ");218}219}220#endif221222//=============================================================================223// Do we Match on this edge index or not? Match only target address & method224uint TailCallNode::match_edge(uint idx) const {225return TypeFunc::Parms <= idx && idx <= TypeFunc::Parms+1;226}227228//=============================================================================229// Do we Match on this edge index or not? Match only target address & oop230uint TailJumpNode::match_edge(uint idx) const {231return TypeFunc::Parms <= idx && idx <= TypeFunc::Parms+1;232}233234//=============================================================================235JVMState::JVMState(ciMethod* method, JVMState* caller) :236_method(method) {237assert(method != NULL, "must be valid call site");238_reexecute = Reexecute_Undefined;239debug_only(_bci = -99); // random garbage value240debug_only(_map = (SafePointNode*)-1);241_caller = caller;242_depth = 1 + (caller == NULL ? 0 : caller->depth());243_locoff = TypeFunc::Parms;244_stkoff = _locoff + _method->max_locals();245_monoff = _stkoff + _method->max_stack();246_scloff = _monoff;247_endoff = _monoff;248_sp = 0;249}250JVMState::JVMState(int stack_size) :251_method(NULL) {252_bci = InvocationEntryBci;253_reexecute = Reexecute_Undefined;254debug_only(_map = (SafePointNode*)-1);255_caller = NULL;256_depth = 1;257_locoff = TypeFunc::Parms;258_stkoff = _locoff;259_monoff = _stkoff + stack_size;260_scloff = _monoff;261_endoff = _monoff;262_sp = 0;263}264265//--------------------------------of_depth-------------------------------------266JVMState* JVMState::of_depth(int d) const {267const JVMState* jvmp = this;268assert(0 < d && (uint)d <= depth(), "oob");269for (int skip = depth() - d; skip > 0; skip--) {270jvmp = jvmp->caller();271}272assert(jvmp->depth() == (uint)d, "found the right one");273return (JVMState*)jvmp;274}275276//-----------------------------same_calls_as-----------------------------------277bool JVMState::same_calls_as(const JVMState* that) const {278if (this == that) return true;279if (this->depth() != that->depth()) return false;280const JVMState* p = this;281const JVMState* q = that;282for (;;) {283if (p->_method != q->_method) return false;284if (p->_method == NULL) return true; // bci is irrelevant285if (p->_bci != q->_bci) return false;286if (p->_reexecute != q->_reexecute) return false;287p = p->caller();288q = q->caller();289if (p == q) return true;290assert(p != NULL && q != NULL, "depth check ensures we don't run off end");291}292}293294//------------------------------debug_start------------------------------------295uint JVMState::debug_start() const {296debug_only(JVMState* jvmroot = of_depth(1));297assert(jvmroot->locoff() <= this->locoff(), "youngest JVMState must be last");298return of_depth(1)->locoff();299}300301//-------------------------------debug_end-------------------------------------302uint JVMState::debug_end() const {303debug_only(JVMState* jvmroot = of_depth(1));304assert(jvmroot->endoff() <= this->endoff(), "youngest JVMState must be last");305return endoff();306}307308//------------------------------debug_depth------------------------------------309uint JVMState::debug_depth() const {310uint total = 0;311for (const JVMState* jvmp = this; jvmp != NULL; jvmp = jvmp->caller()) {312total += jvmp->debug_size();313}314return total;315}316317#ifndef PRODUCT318319//------------------------------format_helper----------------------------------320// Given an allocation (a Chaitin object) and a Node decide if the Node carries321// any defined value or not. If it does, print out the register or constant.322static void format_helper( PhaseRegAlloc *regalloc, outputStream* st, Node *n, const char *msg, uint i, GrowableArray<SafePointScalarObjectNode*> *scobjs ) {323if (n == NULL) { st->print(" NULL"); return; }324if (n->is_SafePointScalarObject()) {325// Scalar replacement.326SafePointScalarObjectNode* spobj = n->as_SafePointScalarObject();327scobjs->append_if_missing(spobj);328int sco_n = scobjs->find(spobj);329assert(sco_n >= 0, "");330st->print(" %s%d]=#ScObj" INT32_FORMAT, msg, i, sco_n);331return;332}333if (regalloc->node_regs_max_index() > 0 &&334OptoReg::is_valid(regalloc->get_reg_first(n))) { // Check for undefined335char buf[50];336regalloc->dump_register(n,buf);337st->print(" %s%d]=%s",msg,i,buf);338} else { // No register, but might be constant339const Type *t = n->bottom_type();340switch (t->base()) {341case Type::Int:342st->print(" %s%d]=#" INT32_FORMAT,msg,i,t->is_int()->get_con());343break;344case Type::AnyPtr:345assert( t == TypePtr::NULL_PTR || n->in_dump(), "" );346st->print(" %s%d]=#NULL",msg,i);347break;348case Type::AryPtr:349case Type::InstPtr:350st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->isa_oopptr()->const_oop()));351break;352case Type::KlassPtr:353st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_klassptr()->klass()));354break;355case Type::MetadataPtr:356st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_metadataptr()->metadata()));357break;358case Type::NarrowOop:359st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_oopptr()->const_oop()));360break;361case Type::RawPtr:362st->print(" %s%d]=#Raw" INTPTR_FORMAT,msg,i,p2i(t->is_rawptr()));363break;364case Type::DoubleCon:365st->print(" %s%d]=#%fD",msg,i,t->is_double_constant()->_d);366break;367case Type::FloatCon:368st->print(" %s%d]=#%fF",msg,i,t->is_float_constant()->_f);369break;370case Type::Long:371st->print(" %s%d]=#" INT64_FORMAT,msg,i,(int64_t)(t->is_long()->get_con()));372break;373case Type::Half:374case Type::Top:375st->print(" %s%d]=_",msg,i);376break;377default: ShouldNotReachHere();378}379}380}381382//------------------------------format-----------------------------------------383void JVMState::format(PhaseRegAlloc *regalloc, const Node *n, outputStream* st) const {384st->print(" #");385if (_method) {386_method->print_short_name(st);387st->print(" @ bci:%d ",_bci);388} else {389st->print_cr(" runtime stub ");390return;391}392if (n->is_MachSafePoint()) {393GrowableArray<SafePointScalarObjectNode*> scobjs;394MachSafePointNode *mcall = n->as_MachSafePoint();395uint i;396// Print locals397for (i = 0; i < (uint)loc_size(); i++)398format_helper(regalloc, st, mcall->local(this, i), "L[", i, &scobjs);399// Print stack400for (i = 0; i < (uint)stk_size(); i++) {401if ((uint)(_stkoff + i) >= mcall->len())402st->print(" oob ");403else404format_helper(regalloc, st, mcall->stack(this, i), "STK[", i, &scobjs);405}406for (i = 0; (int)i < nof_monitors(); i++) {407Node *box = mcall->monitor_box(this, i);408Node *obj = mcall->monitor_obj(this, i);409if (regalloc->node_regs_max_index() > 0 &&410OptoReg::is_valid(regalloc->get_reg_first(box))) {411box = BoxLockNode::box_node(box);412format_helper(regalloc, st, box, "MON-BOX[", i, &scobjs);413} else {414OptoReg::Name box_reg = BoxLockNode::reg(box);415st->print(" MON-BOX%d=%s+%d",416i,417OptoReg::regname(OptoReg::c_frame_pointer),418regalloc->reg2offset(box_reg));419}420const char* obj_msg = "MON-OBJ[";421if (EliminateLocks) {422if (BoxLockNode::box_node(box)->is_eliminated())423obj_msg = "MON-OBJ(LOCK ELIMINATED)[";424}425format_helper(regalloc, st, obj, obj_msg, i, &scobjs);426}427428for (i = 0; i < (uint)scobjs.length(); i++) {429// Scalar replaced objects.430st->cr();431st->print(" # ScObj" INT32_FORMAT " ", i);432SafePointScalarObjectNode* spobj = scobjs.at(i);433ciKlass* cik = spobj->bottom_type()->is_oopptr()->klass();434assert(cik->is_instance_klass() ||435cik->is_array_klass(), "Not supported allocation.");436ciInstanceKlass *iklass = NULL;437if (cik->is_instance_klass()) {438cik->print_name_on(st);439iklass = cik->as_instance_klass();440} else if (cik->is_type_array_klass()) {441cik->as_array_klass()->base_element_type()->print_name_on(st);442st->print("[%d]", spobj->n_fields());443} else if (cik->is_obj_array_klass()) {444ciKlass* cie = cik->as_obj_array_klass()->base_element_klass();445if (cie->is_instance_klass()) {446cie->print_name_on(st);447} else if (cie->is_type_array_klass()) {448cie->as_array_klass()->base_element_type()->print_name_on(st);449} else {450ShouldNotReachHere();451}452st->print("[%d]", spobj->n_fields());453int ndim = cik->as_array_klass()->dimension() - 1;454while (ndim-- > 0) {455st->print("[]");456}457}458st->print("={");459uint nf = spobj->n_fields();460if (nf > 0) {461uint first_ind = spobj->first_index(mcall->jvms());462Node* fld_node = mcall->in(first_ind);463ciField* cifield;464if (iklass != NULL) {465st->print(" [");466cifield = iklass->nonstatic_field_at(0);467cifield->print_name_on(st);468format_helper(regalloc, st, fld_node, ":", 0, &scobjs);469} else {470format_helper(regalloc, st, fld_node, "[", 0, &scobjs);471}472for (uint j = 1; j < nf; j++) {473fld_node = mcall->in(first_ind+j);474if (iklass != NULL) {475st->print(", [");476cifield = iklass->nonstatic_field_at(j);477cifield->print_name_on(st);478format_helper(regalloc, st, fld_node, ":", j, &scobjs);479} else {480format_helper(regalloc, st, fld_node, ", [", j, &scobjs);481}482}483}484st->print(" }");485}486}487st->cr();488if (caller() != NULL) caller()->format(regalloc, n, st);489}490491492void JVMState::dump_spec(outputStream *st) const {493if (_method != NULL) {494bool printed = false;495if (!Verbose) {496// The JVMS dumps make really, really long lines.497// Take out the most boring parts, which are the package prefixes.498char buf[500];499stringStream namest(buf, sizeof(buf));500_method->print_short_name(&namest);501if (namest.count() < sizeof(buf)) {502const char* name = namest.base();503if (name[0] == ' ') ++name;504const char* endcn = strchr(name, ':'); // end of class name505if (endcn == NULL) endcn = strchr(name, '(');506if (endcn == NULL) endcn = name + strlen(name);507while (endcn > name && endcn[-1] != '.' && endcn[-1] != '/')508--endcn;509st->print(" %s", endcn);510printed = true;511}512}513if (!printed)514_method->print_short_name(st);515st->print(" @ bci:%d",_bci);516if(_reexecute == Reexecute_True)517st->print(" reexecute");518} else {519st->print(" runtime stub");520}521if (caller() != NULL) caller()->dump_spec(st);522}523524525void JVMState::dump_on(outputStream* st) const {526bool print_map = _map && !((uintptr_t)_map & 1) &&527((caller() == NULL) || (caller()->map() != _map));528if (print_map) {529if (_map->len() > _map->req()) { // _map->has_exceptions()530Node* ex = _map->in(_map->req()); // _map->next_exception()531// skip the first one; it's already being printed532while (ex != NULL && ex->len() > ex->req()) {533ex = ex->in(ex->req()); // ex->next_exception()534ex->dump(1);535}536}537_map->dump(Verbose ? 2 : 1);538}539if (caller() != NULL) {540caller()->dump_on(st);541}542st->print("JVMS depth=%d loc=%d stk=%d arg=%d mon=%d scalar=%d end=%d mondepth=%d sp=%d bci=%d reexecute=%s method=",543depth(), locoff(), stkoff(), argoff(), monoff(), scloff(), endoff(), monitor_depth(), sp(), bci(), should_reexecute()?"true":"false");544if (_method == NULL) {545st->print_cr("(none)");546} else {547_method->print_name(st);548st->cr();549if (bci() >= 0 && bci() < _method->code_size()) {550st->print(" bc: ");551_method->print_codes_on(bci(), bci()+1, st);552}553}554}555556// Extra way to dump a jvms from the debugger,557// to avoid a bug with C++ member function calls.558void dump_jvms(JVMState* jvms) {559jvms->dump();560}561#endif562563//--------------------------clone_shallow--------------------------------------564JVMState* JVMState::clone_shallow(Compile* C) const {565JVMState* n = has_method() ? new (C) JVMState(_method, _caller) : new (C) JVMState(0);566n->set_bci(_bci);567n->_reexecute = _reexecute;568n->set_locoff(_locoff);569n->set_stkoff(_stkoff);570n->set_monoff(_monoff);571n->set_scloff(_scloff);572n->set_endoff(_endoff);573n->set_sp(_sp);574n->set_map(_map);575return n;576}577578//---------------------------clone_deep----------------------------------------579JVMState* JVMState::clone_deep(Compile* C) const {580JVMState* n = clone_shallow(C);581for (JVMState* p = n; p->_caller != NULL; p = p->_caller) {582p->_caller = p->_caller->clone_shallow(C);583}584assert(n->depth() == depth(), "sanity");585assert(n->debug_depth() == debug_depth(), "sanity");586return n;587}588589/**590* Reset map for all callers591*/592void JVMState::set_map_deep(SafePointNode* map) {593for (JVMState* p = this; p->_caller != NULL; p = p->_caller) {594p->set_map(map);595}596}597598// Adapt offsets in in-array after adding or removing an edge.599// Prerequisite is that the JVMState is used by only one node.600void JVMState::adapt_position(int delta) {601for (JVMState* jvms = this; jvms != NULL; jvms = jvms->caller()) {602jvms->set_locoff(jvms->locoff() + delta);603jvms->set_stkoff(jvms->stkoff() + delta);604jvms->set_monoff(jvms->monoff() + delta);605jvms->set_scloff(jvms->scloff() + delta);606jvms->set_endoff(jvms->endoff() + delta);607}608}609610// Mirror the stack size calculation in the deopt code611// How much stack space would we need at this point in the program in612// case of deoptimization?613int JVMState::interpreter_frame_size() const {614const JVMState* jvms = this;615int size = 0;616int callee_parameters = 0;617int callee_locals = 0;618int extra_args = method()->max_stack() - stk_size();619620while (jvms != NULL) {621int locks = jvms->nof_monitors();622int temps = jvms->stk_size();623bool is_top_frame = (jvms == this);624ciMethod* method = jvms->method();625626int frame_size = BytesPerWord * Interpreter::size_activation(method->max_stack(),627temps + callee_parameters,628extra_args,629locks,630callee_parameters,631callee_locals,632is_top_frame);633size += frame_size;634635callee_parameters = method->size_of_parameters();636callee_locals = method->max_locals();637extra_args = 0;638jvms = jvms->caller();639}640return size + Deoptimization::last_frame_adjust(0, callee_locals) * BytesPerWord;641}642643//=============================================================================644uint CallNode::cmp( const Node &n ) const645{ return _tf == ((CallNode&)n)._tf && _jvms == ((CallNode&)n)._jvms; }646#ifndef PRODUCT647void CallNode::dump_req(outputStream *st) const {648// Dump the required inputs, enclosed in '(' and ')'649uint i; // Exit value of loop650for (i = 0; i < req(); i++) { // For all required inputs651if (i == TypeFunc::Parms) st->print("(");652if (in(i)) st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);653else st->print("_ ");654}655st->print(")");656}657658void CallNode::dump_spec(outputStream *st) const {659st->print(" ");660tf()->dump_on(st);661if (_cnt != COUNT_UNKNOWN) st->print(" C=%f",_cnt);662if (jvms() != NULL) jvms()->dump_spec(st);663}664#endif665666const Type *CallNode::bottom_type() const { return tf()->range(); }667const Type *CallNode::Value(PhaseTransform *phase) const {668if (phase->type(in(0)) == Type::TOP) return Type::TOP;669return tf()->range();670}671672//------------------------------calling_convention-----------------------------673void CallNode::calling_convention( BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt ) const {674// Use the standard compiler calling convention675Matcher::calling_convention( sig_bt, parm_regs, argcnt, true );676}677678679//------------------------------match------------------------------------------680// Construct projections for control, I/O, memory-fields, ..., and681// return result(s) along with their RegMask info682Node *CallNode::match( const ProjNode *proj, const Matcher *match ) {683switch (proj->_con) {684case TypeFunc::Control:685case TypeFunc::I_O:686case TypeFunc::Memory:687return new (match->C) MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);688689case TypeFunc::Parms+1: // For LONG & DOUBLE returns690assert(tf()->_range->field_at(TypeFunc::Parms+1) == Type::HALF, "");691// 2nd half of doubles and longs692return new (match->C) MachProjNode(this,proj->_con, RegMask::Empty, (uint)OptoReg::Bad);693694case TypeFunc::Parms: { // Normal returns695uint ideal_reg = tf()->range()->field_at(TypeFunc::Parms)->ideal_reg();696OptoRegPair regs = is_CallRuntime()697? match->c_return_value(ideal_reg,true) // Calls into C runtime698: match-> return_value(ideal_reg,true); // Calls into compiled Java code699RegMask rm = RegMask(regs.first());700if( OptoReg::is_valid(regs.second()) )701rm.Insert( regs.second() );702return new (match->C) MachProjNode(this,proj->_con,rm,ideal_reg);703}704705case TypeFunc::ReturnAdr:706case TypeFunc::FramePtr:707default:708ShouldNotReachHere();709}710return NULL;711}712713// Do we Match on this edge index or not? Match no edges714uint CallNode::match_edge(uint idx) const {715return 0;716}717718//719// Determine whether the call could modify the field of the specified720// instance at the specified offset.721//722bool CallNode::may_modify(const TypeOopPtr *t_oop, PhaseTransform *phase) {723assert((t_oop != NULL), "sanity");724if (t_oop->is_known_instance()) {725// The instance_id is set only for scalar-replaceable allocations which726// are not passed as arguments according to Escape Analysis.727return false;728}729if (t_oop->is_ptr_to_boxed_value()) {730ciKlass* boxing_klass = t_oop->klass();731if (is_CallStaticJava() && as_CallStaticJava()->is_boxing_method()) {732// Skip unrelated boxing methods.733Node* proj = proj_out(TypeFunc::Parms);734if ((proj == NULL) || (phase->type(proj)->is_instptr()->klass() != boxing_klass)) {735return false;736}737}738if (is_CallJava() && as_CallJava()->method() != NULL) {739ciMethod* meth = as_CallJava()->method();740if (meth->is_accessor()) {741return false;742}743// May modify (by reflection) if an boxing object is passed744// as argument or returned.745Node* proj = returns_pointer() ? proj_out(TypeFunc::Parms) : NULL;746if (proj != NULL) {747const TypeInstPtr* inst_t = phase->type(proj)->isa_instptr();748if ((inst_t != NULL) && (!inst_t->klass_is_exact() ||749(inst_t->klass() == boxing_klass))) {750return true;751}752}753const TypeTuple* d = tf()->domain();754for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {755const TypeInstPtr* inst_t = d->field_at(i)->isa_instptr();756if ((inst_t != NULL) && (!inst_t->klass_is_exact() ||757(inst_t->klass() == boxing_klass))) {758return true;759}760}761return false;762}763}764return true;765}766767// Does this call have a direct reference to n other than debug information?768bool CallNode::has_non_debug_use(Node *n) {769const TypeTuple * d = tf()->domain();770for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {771Node *arg = in(i);772if (arg == n) {773return true;774}775}776return false;777}778779// Returns the unique CheckCastPP of a call780// or 'this' if there are several CheckCastPP or unexpected uses781// or returns NULL if there is no one.782Node *CallNode::result_cast() {783Node *cast = NULL;784785Node *p = proj_out(TypeFunc::Parms);786if (p == NULL)787return NULL;788789for (DUIterator_Fast imax, i = p->fast_outs(imax); i < imax; i++) {790Node *use = p->fast_out(i);791if (use->is_CheckCastPP()) {792if (cast != NULL) {793return this; // more than 1 CheckCastPP794}795cast = use;796} else if (!use->is_Initialize() &&797!use->is_AddP()) {798// Expected uses are restricted to a CheckCastPP, an Initialize799// node, and AddP nodes. If we encounter any other use (a Phi800// node can be seen in rare cases) return this to prevent801// incorrect optimizations.802return this;803}804}805return cast;806}807808809void CallNode::extract_projections(CallProjections* projs, bool separate_io_proj) {810projs->fallthrough_proj = NULL;811projs->fallthrough_catchproj = NULL;812projs->fallthrough_ioproj = NULL;813projs->catchall_ioproj = NULL;814projs->catchall_catchproj = NULL;815projs->fallthrough_memproj = NULL;816projs->catchall_memproj = NULL;817projs->resproj = NULL;818projs->exobj = NULL;819820for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {821ProjNode *pn = fast_out(i)->as_Proj();822if (pn->outcnt() == 0) continue;823switch (pn->_con) {824case TypeFunc::Control:825{826// For Control (fallthrough) and I_O (catch_all_index) we have CatchProj -> Catch -> Proj827projs->fallthrough_proj = pn;828DUIterator_Fast jmax, j = pn->fast_outs(jmax);829const Node *cn = pn->fast_out(j);830if (cn->is_Catch()) {831ProjNode *cpn = NULL;832for (DUIterator_Fast kmax, k = cn->fast_outs(kmax); k < kmax; k++) {833cpn = cn->fast_out(k)->as_Proj();834assert(cpn->is_CatchProj(), "must be a CatchProjNode");835if (cpn->_con == CatchProjNode::fall_through_index)836projs->fallthrough_catchproj = cpn;837else {838assert(cpn->_con == CatchProjNode::catch_all_index, "must be correct index.");839projs->catchall_catchproj = cpn;840}841}842}843break;844}845case TypeFunc::I_O:846if (pn->_is_io_use)847projs->catchall_ioproj = pn;848else849projs->fallthrough_ioproj = pn;850for (DUIterator j = pn->outs(); pn->has_out(j); j++) {851Node* e = pn->out(j);852if (e->Opcode() == Op_CreateEx && e->in(0)->is_CatchProj() && e->outcnt() > 0) {853assert(projs->exobj == NULL, "only one");854projs->exobj = e;855}856}857break;858case TypeFunc::Memory:859if (pn->_is_io_use)860projs->catchall_memproj = pn;861else862projs->fallthrough_memproj = pn;863break;864case TypeFunc::Parms:865projs->resproj = pn;866break;867default:868assert(false, "unexpected projection from allocation node.");869}870}871872// The resproj may not exist because the result couuld be ignored873// and the exception object may not exist if an exception handler874// swallows the exception but all the other must exist and be found.875assert(projs->fallthrough_proj != NULL, "must be found");876assert(Compile::current()->inlining_incrementally() || projs->fallthrough_catchproj != NULL, "must be found");877assert(Compile::current()->inlining_incrementally() || projs->fallthrough_memproj != NULL, "must be found");878assert(Compile::current()->inlining_incrementally() || projs->fallthrough_ioproj != NULL, "must be found");879assert(Compile::current()->inlining_incrementally() || projs->catchall_catchproj != NULL, "must be found");880if (separate_io_proj) {881assert(Compile::current()->inlining_incrementally() || projs->catchall_memproj != NULL, "must be found");882assert(Compile::current()->inlining_incrementally() || projs->catchall_ioproj != NULL, "must be found");883}884}885886Node *CallNode::Ideal(PhaseGVN *phase, bool can_reshape) {887CallGenerator* cg = generator();888if (can_reshape && cg != NULL && cg->is_mh_late_inline() && !cg->already_attempted()) {889// Check whether this MH handle call becomes a candidate for inlining890ciMethod* callee = cg->method();891vmIntrinsics::ID iid = callee->intrinsic_id();892if (iid == vmIntrinsics::_invokeBasic) {893if (in(TypeFunc::Parms)->Opcode() == Op_ConP) {894phase->C->prepend_late_inline(cg);895set_generator(NULL);896}897} else {898assert(callee->has_member_arg(), "wrong type of call?");899if (in(TypeFunc::Parms + callee->arg_size() - 1)->Opcode() == Op_ConP) {900phase->C->prepend_late_inline(cg);901set_generator(NULL);902}903}904}905return SafePointNode::Ideal(phase, can_reshape);906}907908909//=============================================================================910uint CallJavaNode::size_of() const { return sizeof(*this); }911uint CallJavaNode::cmp( const Node &n ) const {912CallJavaNode &call = (CallJavaNode&)n;913return CallNode::cmp(call) && _method == call._method;914}915#ifndef PRODUCT916void CallJavaNode::dump_spec(outputStream *st) const {917if( _method ) _method->print_short_name(st);918CallNode::dump_spec(st);919}920#endif921922//=============================================================================923uint CallStaticJavaNode::size_of() const { return sizeof(*this); }924uint CallStaticJavaNode::cmp( const Node &n ) const {925CallStaticJavaNode &call = (CallStaticJavaNode&)n;926return CallJavaNode::cmp(call);927}928929//----------------------------uncommon_trap_request----------------------------930// If this is an uncommon trap, return the request code, else zero.931int CallStaticJavaNode::uncommon_trap_request() const {932if (_name != NULL && !strcmp(_name, "uncommon_trap")) {933return extract_uncommon_trap_request(this);934}935return 0;936}937int CallStaticJavaNode::extract_uncommon_trap_request(const Node* call) {938#ifndef PRODUCT939if (!(call->req() > TypeFunc::Parms &&940call->in(TypeFunc::Parms) != NULL &&941call->in(TypeFunc::Parms)->is_Con())) {942assert(in_dump() != 0, "OK if dumping");943tty->print("[bad uncommon trap]");944return 0;945}946#endif947return call->in(TypeFunc::Parms)->bottom_type()->is_int()->get_con();948}949950#ifndef PRODUCT951void CallStaticJavaNode::dump_spec(outputStream *st) const {952st->print("# Static ");953if (_name != NULL) {954st->print("%s", _name);955int trap_req = uncommon_trap_request();956if (trap_req != 0) {957char buf[100];958st->print("(%s)",959Deoptimization::format_trap_request(buf, sizeof(buf),960trap_req));961}962st->print(" ");963}964CallJavaNode::dump_spec(st);965}966#endif967968//=============================================================================969uint CallDynamicJavaNode::size_of() const { return sizeof(*this); }970uint CallDynamicJavaNode::cmp( const Node &n ) const {971CallDynamicJavaNode &call = (CallDynamicJavaNode&)n;972return CallJavaNode::cmp(call);973}974#ifndef PRODUCT975void CallDynamicJavaNode::dump_spec(outputStream *st) const {976st->print("# Dynamic ");977CallJavaNode::dump_spec(st);978}979#endif980981//=============================================================================982uint CallRuntimeNode::size_of() const { return sizeof(*this); }983uint CallRuntimeNode::cmp( const Node &n ) const {984CallRuntimeNode &call = (CallRuntimeNode&)n;985return CallNode::cmp(call) && !strcmp(_name,call._name);986}987#ifndef PRODUCT988void CallRuntimeNode::dump_spec(outputStream *st) const {989st->print("# ");990st->print("%s", _name);991CallNode::dump_spec(st);992}993#endif994995//------------------------------calling_convention-----------------------------996void CallRuntimeNode::calling_convention( BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt ) const {997Matcher::c_calling_convention( sig_bt, parm_regs, argcnt );998}9991000//=============================================================================1001//------------------------------calling_convention-----------------------------100210031004//=============================================================================1005#ifndef PRODUCT1006void CallLeafNode::dump_spec(outputStream *st) const {1007st->print("# ");1008st->print("%s", _name);1009CallNode::dump_spec(st);1010}1011#endif10121013//=============================================================================10141015void SafePointNode::set_local(JVMState* jvms, uint idx, Node *c) {1016assert(verify_jvms(jvms), "jvms must match");1017int loc = jvms->locoff() + idx;1018if (in(loc)->is_top() && idx > 0 && !c->is_top() ) {1019// If current local idx is top then local idx - 1 could1020// be a long/double that needs to be killed since top could1021// represent the 2nd half ofthe long/double.1022uint ideal = in(loc -1)->ideal_reg();1023if (ideal == Op_RegD || ideal == Op_RegL) {1024// set other (low index) half to top1025set_req(loc - 1, in(loc));1026}1027}1028set_req(loc, c);1029}10301031uint SafePointNode::size_of() const { return sizeof(*this); }1032uint SafePointNode::cmp( const Node &n ) const {1033return (&n == this); // Always fail except on self1034}10351036//-------------------------set_next_exception----------------------------------1037void SafePointNode::set_next_exception(SafePointNode* n) {1038assert(n == NULL || n->Opcode() == Op_SafePoint, "correct value for next_exception");1039if (len() == req()) {1040if (n != NULL) add_prec(n);1041} else {1042set_prec(req(), n);1043}1044}104510461047//----------------------------next_exception-----------------------------------1048SafePointNode* SafePointNode::next_exception() const {1049if (len() == req()) {1050return NULL;1051} else {1052Node* n = in(req());1053assert(n == NULL || n->Opcode() == Op_SafePoint, "no other uses of prec edges");1054return (SafePointNode*) n;1055}1056}105710581059//------------------------------Ideal------------------------------------------1060// Skip over any collapsed Regions1061Node *SafePointNode::Ideal(PhaseGVN *phase, bool can_reshape) {1062return remove_dead_region(phase, can_reshape) ? this : NULL;1063}10641065//------------------------------Identity---------------------------------------1066// Remove obviously duplicate safepoints1067Node *SafePointNode::Identity( PhaseTransform *phase ) {10681069// If you have back to back safepoints, remove one1070if( in(TypeFunc::Control)->is_SafePoint() )1071return in(TypeFunc::Control);10721073if( in(0)->is_Proj() ) {1074Node *n0 = in(0)->in(0);1075// Check if he is a call projection (except Leaf Call)1076if( n0->is_Catch() ) {1077n0 = n0->in(0)->in(0);1078assert( n0->is_Call(), "expect a call here" );1079}1080if( n0->is_Call() && n0->as_Call()->guaranteed_safepoint() ) {1081// Useless Safepoint, so remove it1082return in(TypeFunc::Control);1083}1084}10851086return this;1087}10881089//------------------------------Value------------------------------------------1090const Type *SafePointNode::Value( PhaseTransform *phase ) const {1091if( phase->type(in(0)) == Type::TOP ) return Type::TOP;1092if( phase->eqv( in(0), this ) ) return Type::TOP; // Dead infinite loop1093return Type::CONTROL;1094}10951096#ifndef PRODUCT1097void SafePointNode::dump_spec(outputStream *st) const {1098st->print(" SafePoint ");1099_replaced_nodes.dump(st);1100}1101#endif11021103const RegMask &SafePointNode::in_RegMask(uint idx) const {1104if( idx < TypeFunc::Parms ) return RegMask::Empty;1105// Values outside the domain represent debug info1106return *(Compile::current()->matcher()->idealreg2debugmask[in(idx)->ideal_reg()]);1107}1108const RegMask &SafePointNode::out_RegMask() const {1109return RegMask::Empty;1110}111111121113void SafePointNode::grow_stack(JVMState* jvms, uint grow_by) {1114assert((int)grow_by > 0, "sanity");1115int monoff = jvms->monoff();1116int scloff = jvms->scloff();1117int endoff = jvms->endoff();1118assert(endoff == (int)req(), "no other states or debug info after me");1119Node* top = Compile::current()->top();1120for (uint i = 0; i < grow_by; i++) {1121ins_req(monoff, top);1122}1123jvms->set_monoff(monoff + grow_by);1124jvms->set_scloff(scloff + grow_by);1125jvms->set_endoff(endoff + grow_by);1126}11271128void SafePointNode::push_monitor(const FastLockNode *lock) {1129// Add a LockNode, which points to both the original BoxLockNode (the1130// stack space for the monitor) and the Object being locked.1131const int MonitorEdges = 2;1132assert(JVMState::logMonitorEdges == exact_log2(MonitorEdges), "correct MonitorEdges");1133assert(req() == jvms()->endoff(), "correct sizing");1134int nextmon = jvms()->scloff();1135if (GenerateSynchronizationCode) {1136ins_req(nextmon, lock->box_node());1137ins_req(nextmon+1, lock->obj_node());1138} else {1139Node* top = Compile::current()->top();1140ins_req(nextmon, top);1141ins_req(nextmon, top);1142}1143jvms()->set_scloff(nextmon + MonitorEdges);1144jvms()->set_endoff(req());1145}11461147void SafePointNode::pop_monitor() {1148// Delete last monitor from debug info1149debug_only(int num_before_pop = jvms()->nof_monitors());1150const int MonitorEdges = 2;1151assert(JVMState::logMonitorEdges == exact_log2(MonitorEdges), "correct MonitorEdges");1152int scloff = jvms()->scloff();1153int endoff = jvms()->endoff();1154int new_scloff = scloff - MonitorEdges;1155int new_endoff = endoff - MonitorEdges;1156jvms()->set_scloff(new_scloff);1157jvms()->set_endoff(new_endoff);1158while (scloff > new_scloff) del_req_ordered(--scloff);1159assert(jvms()->nof_monitors() == num_before_pop-1, "");1160}11611162Node *SafePointNode::peek_monitor_box() const {1163int mon = jvms()->nof_monitors() - 1;1164assert(mon >= 0, "most have a monitor");1165return monitor_box(jvms(), mon);1166}11671168Node *SafePointNode::peek_monitor_obj() const {1169int mon = jvms()->nof_monitors() - 1;1170assert(mon >= 0, "most have a monitor");1171return monitor_obj(jvms(), mon);1172}11731174// Do we Match on this edge index or not? Match no edges1175uint SafePointNode::match_edge(uint idx) const {1176if( !needs_polling_address_input() )1177return 0;11781179return (TypeFunc::Parms == idx);1180}11811182void SafePointNode::disconnect_from_root(PhaseIterGVN *igvn) {1183assert(Opcode() == Op_SafePoint, "only value for safepoint in loops");1184int nb = igvn->C->root()->find_prec_edge(this);1185if (nb != -1) {1186igvn->C->root()->rm_prec(nb);1187}1188}11891190//============== SafePointScalarObjectNode ==============11911192SafePointScalarObjectNode::SafePointScalarObjectNode(const TypeOopPtr* tp,1193#ifdef ASSERT1194AllocateNode* alloc,1195#endif1196uint first_index,1197uint n_fields) :1198TypeNode(tp, 1), // 1 control input -- seems required. Get from root.1199#ifdef ASSERT1200_alloc(alloc),1201#endif1202_first_index(first_index),1203_n_fields(n_fields)1204{1205init_class_id(Class_SafePointScalarObject);1206}12071208// Do not allow value-numbering for SafePointScalarObject node.1209uint SafePointScalarObjectNode::hash() const { return NO_HASH; }1210uint SafePointScalarObjectNode::cmp( const Node &n ) const {1211return (&n == this); // Always fail except on self1212}12131214uint SafePointScalarObjectNode::ideal_reg() const {1215return 0; // No matching to machine instruction1216}12171218const RegMask &SafePointScalarObjectNode::in_RegMask(uint idx) const {1219return *(Compile::current()->matcher()->idealreg2debugmask[in(idx)->ideal_reg()]);1220}12211222const RegMask &SafePointScalarObjectNode::out_RegMask() const {1223return RegMask::Empty;1224}12251226uint SafePointScalarObjectNode::match_edge(uint idx) const {1227return 0;1228}12291230SafePointScalarObjectNode*1231SafePointScalarObjectNode::clone(Dict* sosn_map) const {1232void* cached = (*sosn_map)[(void*)this];1233if (cached != NULL) {1234return (SafePointScalarObjectNode*)cached;1235}1236SafePointScalarObjectNode* res = (SafePointScalarObjectNode*)Node::clone();1237sosn_map->Insert((void*)this, (void*)res);1238return res;1239}124012411242#ifndef PRODUCT1243void SafePointScalarObjectNode::dump_spec(outputStream *st) const {1244st->print(" # fields@[%d..%d]", first_index(),1245first_index() + n_fields() - 1);1246}12471248#endif12491250//=============================================================================1251uint AllocateNode::size_of() const { return sizeof(*this); }12521253AllocateNode::AllocateNode(Compile* C, const TypeFunc *atype,1254Node *ctrl, Node *mem, Node *abio,1255Node *size, Node *klass_node, Node *initial_test)1256: CallNode(atype, NULL, TypeRawPtr::BOTTOM)1257{1258init_class_id(Class_Allocate);1259init_flags(Flag_is_macro);1260_is_scalar_replaceable = false;1261_is_non_escaping = false;1262Node *topnode = C->top();12631264init_req( TypeFunc::Control , ctrl );1265init_req( TypeFunc::I_O , abio );1266init_req( TypeFunc::Memory , mem );1267init_req( TypeFunc::ReturnAdr, topnode );1268init_req( TypeFunc::FramePtr , topnode );1269init_req( AllocSize , size);1270init_req( KlassNode , klass_node);1271init_req( InitialTest , initial_test);1272init_req( ALength , topnode);1273C->add_macro_node(this);1274}12751276//=============================================================================1277Node* AllocateArrayNode::Ideal(PhaseGVN *phase, bool can_reshape) {1278if (remove_dead_region(phase, can_reshape)) return this;1279// Don't bother trying to transform a dead node1280if (in(0) && in(0)->is_top()) return NULL;12811282const Type* type = phase->type(Ideal_length());1283if (type->isa_int() && type->is_int()->_hi < 0) {1284if (can_reshape) {1285PhaseIterGVN *igvn = phase->is_IterGVN();1286// Unreachable fall through path (negative array length),1287// the allocation can only throw so disconnect it.1288Node* proj = proj_out(TypeFunc::Control);1289Node* catchproj = NULL;1290if (proj != NULL) {1291for (DUIterator_Fast imax, i = proj->fast_outs(imax); i < imax; i++) {1292Node *cn = proj->fast_out(i);1293if (cn->is_Catch()) {1294catchproj = cn->as_Multi()->proj_out(CatchProjNode::fall_through_index);1295break;1296}1297}1298}1299if (catchproj != NULL && catchproj->outcnt() > 0 &&1300(catchproj->outcnt() > 1 ||1301catchproj->unique_out()->Opcode() != Op_Halt)) {1302assert(catchproj->is_CatchProj(), "must be a CatchProjNode");1303Node* nproj = catchproj->clone();1304igvn->register_new_node_with_optimizer(nproj);13051306Node *frame = new (phase->C) ParmNode( phase->C->start(), TypeFunc::FramePtr );1307frame = phase->transform(frame);1308// Halt & Catch Fire1309Node *halt = new (phase->C) HaltNode( nproj, frame );1310phase->C->root()->add_req(halt);1311phase->transform(halt);13121313igvn->replace_node(catchproj, phase->C->top());1314return this;1315}1316} else {1317// Can't correct it during regular GVN so register for IGVN1318phase->C->record_for_igvn(this);1319}1320}1321return NULL;1322}13231324// Retrieve the length from the AllocateArrayNode. Narrow the type with a1325// CastII, if appropriate. If we are not allowed to create new nodes, and1326// a CastII is appropriate, return NULL.1327Node *AllocateArrayNode::make_ideal_length(const TypeOopPtr* oop_type, PhaseTransform *phase, bool allow_new_nodes) {1328Node *length = in(AllocateNode::ALength);1329assert(length != NULL, "length is not null");13301331const TypeInt* length_type = phase->find_int_type(length);1332const TypeAryPtr* ary_type = oop_type->isa_aryptr();13331334if (ary_type != NULL && length_type != NULL) {1335const TypeInt* narrow_length_type = ary_type->narrow_size_type(length_type);1336if (narrow_length_type != length_type) {1337// Assert one of:1338// - the narrow_length is 01339// - the narrow_length is not wider than length1340assert(narrow_length_type == TypeInt::ZERO ||1341length_type->is_con() && narrow_length_type->is_con() &&1342(narrow_length_type->_hi <= length_type->_lo) ||1343(narrow_length_type->_hi <= length_type->_hi &&1344narrow_length_type->_lo >= length_type->_lo),1345"narrow type must be narrower than length type");13461347// Return NULL if new nodes are not allowed1348if (!allow_new_nodes) return NULL;1349// Create a cast which is control dependent on the initialization to1350// propagate the fact that the array length must be positive.1351length = new (phase->C) CastIINode(length, narrow_length_type);1352length->set_req(0, initialization()->proj_out(0));1353}1354}13551356return length;1357}13581359//=============================================================================1360uint LockNode::size_of() const { return sizeof(*this); }13611362// Redundant lock elimination1363//1364// There are various patterns of locking where we release and1365// immediately reacquire a lock in a piece of code where no operations1366// occur in between that would be observable. In those cases we can1367// skip releasing and reacquiring the lock without violating any1368// fairness requirements. Doing this around a loop could cause a lock1369// to be held for a very long time so we concentrate on non-looping1370// control flow. We also require that the operations are fully1371// redundant meaning that we don't introduce new lock operations on1372// some paths so to be able to eliminate it on others ala PRE. This1373// would probably require some more extensive graph manipulation to1374// guarantee that the memory edges were all handled correctly.1375//1376// Assuming p is a simple predicate which can't trap in any way and s1377// is a synchronized method consider this code:1378//1379// s();1380// if (p)1381// s();1382// else1383// s();1384// s();1385//1386// 1. The unlocks of the first call to s can be eliminated if the1387// locks inside the then and else branches are eliminated.1388//1389// 2. The unlocks of the then and else branches can be eliminated if1390// the lock of the final call to s is eliminated.1391//1392// Either of these cases subsumes the simple case of sequential control flow1393//1394// Addtionally we can eliminate versions without the else case:1395//1396// s();1397// if (p)1398// s();1399// s();1400//1401// 3. In this case we eliminate the unlock of the first s, the lock1402// and unlock in the then case and the lock in the final s.1403//1404// Note also that in all these cases the then/else pieces don't have1405// to be trivial as long as they begin and end with synchronization1406// operations.1407//1408// s();1409// if (p)1410// s();1411// f();1412// s();1413// s();1414//1415// The code will work properly for this case, leaving in the unlock1416// before the call to f and the relock after it.1417//1418// A potentially interesting case which isn't handled here is when the1419// locking is partially redundant.1420//1421// s();1422// if (p)1423// s();1424//1425// This could be eliminated putting unlocking on the else case and1426// eliminating the first unlock and the lock in the then side.1427// Alternatively the unlock could be moved out of the then side so it1428// was after the merge and the first unlock and second lock1429// eliminated. This might require less manipulation of the memory1430// state to get correct.1431//1432// Additionally we might allow work between a unlock and lock before1433// giving up eliminating the locks. The current code disallows any1434// conditional control flow between these operations. A formulation1435// similar to partial redundancy elimination computing the1436// availability of unlocking and the anticipatability of locking at a1437// program point would allow detection of fully redundant locking with1438// some amount of work in between. I'm not sure how often I really1439// think that would occur though. Most of the cases I've seen1440// indicate it's likely non-trivial work would occur in between.1441// There may be other more complicated constructs where we could1442// eliminate locking but I haven't seen any others appear as hot or1443// interesting.1444//1445// Locking and unlocking have a canonical form in ideal that looks1446// roughly like this:1447//1448// <obj>1449// | \\------+1450// | \ \1451// | BoxLock \1452// | | | \1453// | | \ \1454// | | FastLock1455// | | /1456// | | /1457// | | |1458//1459// Lock1460// |1461// Proj #01462// |1463// MembarAcquire1464// |1465// Proj #01466//1467// MembarRelease1468// |1469// Proj #01470// |1471// Unlock1472// |1473// Proj #01474//1475//1476// This code proceeds by processing Lock nodes during PhaseIterGVN1477// and searching back through its control for the proper code1478// patterns. Once it finds a set of lock and unlock operations to1479// eliminate they are marked as eliminatable which causes the1480// expansion of the Lock and Unlock macro nodes to make the operation a NOP1481//1482//=============================================================================14831484//1485// Utility function to skip over uninteresting control nodes. Nodes skipped are:1486// - copy regions. (These may not have been optimized away yet.)1487// - eliminated locking nodes1488//1489static Node *next_control(Node *ctrl) {1490if (ctrl == NULL)1491return NULL;1492while (1) {1493if (ctrl->is_Region()) {1494RegionNode *r = ctrl->as_Region();1495Node *n = r->is_copy();1496if (n == NULL)1497break; // hit a region, return it1498else1499ctrl = n;1500} else if (ctrl->is_Proj()) {1501Node *in0 = ctrl->in(0);1502if (in0->is_AbstractLock() && in0->as_AbstractLock()->is_eliminated()) {1503ctrl = in0->in(0);1504} else {1505break;1506}1507} else {1508break; // found an interesting control1509}1510}1511return ctrl;1512}1513//1514// Given a control, see if it's the control projection of an Unlock which1515// operating on the same object as lock.1516//1517bool AbstractLockNode::find_matching_unlock(const Node* ctrl, LockNode* lock,1518GrowableArray<AbstractLockNode*> &lock_ops) {1519ProjNode *ctrl_proj = (ctrl->is_Proj()) ? ctrl->as_Proj() : NULL;1520if (ctrl_proj != NULL && ctrl_proj->_con == TypeFunc::Control) {1521Node *n = ctrl_proj->in(0);1522if (n != NULL && n->is_Unlock()) {1523UnlockNode *unlock = n->as_Unlock();1524if (lock->obj_node()->eqv_uncast(unlock->obj_node()) &&1525BoxLockNode::same_slot(lock->box_node(), unlock->box_node()) &&1526!unlock->is_eliminated()) {1527lock_ops.append(unlock);1528return true;1529}1530}1531}1532return false;1533}15341535//1536// Find the lock matching an unlock. Returns null if a safepoint1537// or complicated control is encountered first.1538LockNode *AbstractLockNode::find_matching_lock(UnlockNode* unlock) {1539LockNode *lock_result = NULL;1540// find the matching lock, or an intervening safepoint1541Node *ctrl = next_control(unlock->in(0));1542while (1) {1543assert(ctrl != NULL, "invalid control graph");1544assert(!ctrl->is_Start(), "missing lock for unlock");1545if (ctrl->is_top()) break; // dead control path1546if (ctrl->is_Proj()) ctrl = ctrl->in(0);1547if (ctrl->is_SafePoint()) {1548break; // found a safepoint (may be the lock we are searching for)1549} else if (ctrl->is_Region()) {1550// Check for a simple diamond pattern. Punt on anything more complicated1551if (ctrl->req() == 3 && ctrl->in(1) != NULL && ctrl->in(2) != NULL) {1552Node *in1 = next_control(ctrl->in(1));1553Node *in2 = next_control(ctrl->in(2));1554if (((in1->is_IfTrue() && in2->is_IfFalse()) ||1555(in2->is_IfTrue() && in1->is_IfFalse())) && (in1->in(0) == in2->in(0))) {1556ctrl = next_control(in1->in(0)->in(0));1557} else {1558break;1559}1560} else {1561break;1562}1563} else {1564ctrl = next_control(ctrl->in(0)); // keep searching1565}1566}1567if (ctrl->is_Lock()) {1568LockNode *lock = ctrl->as_Lock();1569if (lock->obj_node()->eqv_uncast(unlock->obj_node()) &&1570BoxLockNode::same_slot(lock->box_node(), unlock->box_node())) {1571lock_result = lock;1572}1573}1574return lock_result;1575}15761577// This code corresponds to case 3 above.15781579bool AbstractLockNode::find_lock_and_unlock_through_if(Node* node, LockNode* lock,1580GrowableArray<AbstractLockNode*> &lock_ops) {1581Node* if_node = node->in(0);1582bool if_true = node->is_IfTrue();15831584if (if_node->is_If() && if_node->outcnt() == 2 && (if_true || node->is_IfFalse())) {1585Node *lock_ctrl = next_control(if_node->in(0));1586if (find_matching_unlock(lock_ctrl, lock, lock_ops)) {1587Node* lock1_node = NULL;1588ProjNode* proj = if_node->as_If()->proj_out(!if_true);1589if (if_true) {1590if (proj->is_IfFalse() && proj->outcnt() == 1) {1591lock1_node = proj->unique_out();1592}1593} else {1594if (proj->is_IfTrue() && proj->outcnt() == 1) {1595lock1_node = proj->unique_out();1596}1597}1598if (lock1_node != NULL && lock1_node->is_Lock()) {1599LockNode *lock1 = lock1_node->as_Lock();1600if (lock->obj_node()->eqv_uncast(lock1->obj_node()) &&1601BoxLockNode::same_slot(lock->box_node(), lock1->box_node()) &&1602!lock1->is_eliminated()) {1603lock_ops.append(lock1);1604return true;1605}1606}1607}1608}16091610lock_ops.trunc_to(0);1611return false;1612}16131614bool AbstractLockNode::find_unlocks_for_region(const RegionNode* region, LockNode* lock,1615GrowableArray<AbstractLockNode*> &lock_ops) {1616// check each control merging at this point for a matching unlock.1617// in(0) should be self edge so skip it.1618for (int i = 1; i < (int)region->req(); i++) {1619Node *in_node = next_control(region->in(i));1620if (in_node != NULL) {1621if (find_matching_unlock(in_node, lock, lock_ops)) {1622// found a match so keep on checking.1623continue;1624} else if (find_lock_and_unlock_through_if(in_node, lock, lock_ops)) {1625continue;1626}16271628// If we fall through to here then it was some kind of node we1629// don't understand or there wasn't a matching unlock, so give1630// up trying to merge locks.1631lock_ops.trunc_to(0);1632return false;1633}1634}1635return true;16361637}16381639#ifndef PRODUCT1640//1641// Create a counter which counts the number of times this lock is acquired1642//1643void AbstractLockNode::create_lock_counter(JVMState* state) {1644_counter = OptoRuntime::new_named_counter(state, NamedCounter::LockCounter);1645}16461647void AbstractLockNode::set_eliminated_lock_counter() {1648if (_counter) {1649// Update the counter to indicate that this lock was eliminated.1650// The counter update code will stay around even though the1651// optimizer will eliminate the lock operation itself.1652_counter->set_tag(NamedCounter::EliminatedLockCounter);1653}1654}1655#endif16561657//=============================================================================1658Node *LockNode::Ideal(PhaseGVN *phase, bool can_reshape) {16591660// perform any generic optimizations first (returns 'this' or NULL)1661Node *result = SafePointNode::Ideal(phase, can_reshape);1662if (result != NULL) return result;1663// Don't bother trying to transform a dead node1664if (in(0) && in(0)->is_top()) return NULL;16651666// Now see if we can optimize away this lock. We don't actually1667// remove the locking here, we simply set the _eliminate flag which1668// prevents macro expansion from expanding the lock. Since we don't1669// modify the graph, the value returned from this function is the1670// one computed above.1671if (can_reshape && EliminateLocks && !is_non_esc_obj()) {1672//1673// If we are locking an unescaped object, the lock/unlock is unnecessary1674//1675ConnectionGraph *cgr = phase->C->congraph();1676if (cgr != NULL && cgr->not_global_escape(obj_node())) {1677assert(!is_eliminated() || is_coarsened(), "sanity");1678// The lock could be marked eliminated by lock coarsening1679// code during first IGVN before EA. Replace coarsened flag1680// to eliminate all associated locks/unlocks.1681#ifdef ASSERT1682this->log_lock_optimization(phase->C,"eliminate_lock_set_non_esc1");1683#endif1684this->set_non_esc_obj();1685return result;1686}16871688//1689// Try lock coarsening1690//1691PhaseIterGVN* iter = phase->is_IterGVN();1692if (iter != NULL && !is_eliminated()) {16931694GrowableArray<AbstractLockNode*> lock_ops;16951696Node *ctrl = next_control(in(0));16971698// now search back for a matching Unlock1699if (find_matching_unlock(ctrl, this, lock_ops)) {1700// found an unlock directly preceding this lock. This is the1701// case of single unlock directly control dependent on a1702// single lock which is the trivial version of case 1 or 2.1703} else if (ctrl->is_Region() ) {1704if (find_unlocks_for_region(ctrl->as_Region(), this, lock_ops)) {1705// found lock preceded by multiple unlocks along all paths1706// joining at this point which is case 3 in description above.1707}1708} else {1709// see if this lock comes from either half of an if and the1710// predecessors merges unlocks and the other half of the if1711// performs a lock.1712if (find_lock_and_unlock_through_if(ctrl, this, lock_ops)) {1713// found unlock splitting to an if with locks on both branches.1714}1715}17161717if (lock_ops.length() > 0) {1718// add ourselves to the list of locks to be eliminated.1719lock_ops.append(this);17201721#ifndef PRODUCT1722if (PrintEliminateLocks) {1723int locks = 0;1724int unlocks = 0;1725for (int i = 0; i < lock_ops.length(); i++) {1726AbstractLockNode* lock = lock_ops.at(i);1727if (lock->Opcode() == Op_Lock)1728locks++;1729else1730unlocks++;1731if (Verbose) {1732lock->dump(1);1733}1734}1735tty->print_cr("***Eliminated %d unlocks and %d locks", unlocks, locks);1736}1737#endif17381739// for each of the identified locks, mark them1740// as eliminatable1741for (int i = 0; i < lock_ops.length(); i++) {1742AbstractLockNode* lock = lock_ops.at(i);17431744// Mark it eliminated by coarsening and update any counters1745#ifdef ASSERT1746lock->log_lock_optimization(phase->C, "eliminate_lock_set_coarsened");1747#endif1748lock->set_coarsened();1749}1750} else if (ctrl->is_Region() &&1751iter->_worklist.member(ctrl)) {1752// We weren't able to find any opportunities but the region this1753// lock is control dependent on hasn't been processed yet so put1754// this lock back on the worklist so we can check again once any1755// region simplification has occurred.1756iter->_worklist.push(this);1757}1758}1759}17601761return result;1762}17631764//=============================================================================1765bool LockNode::is_nested_lock_region() {1766return is_nested_lock_region(NULL);1767}17681769// p is used for access to compilation log; no logging if NULL1770bool LockNode::is_nested_lock_region(Compile * c) {1771BoxLockNode* box = box_node()->as_BoxLock();1772int stk_slot = box->stack_slot();1773if (stk_slot <= 0) {1774#ifdef ASSERT1775this->log_lock_optimization(c, "eliminate_lock_INLR_1");1776#endif1777return false; // External lock or it is not Box (Phi node).1778}17791780// Ignore complex cases: merged locks or multiple locks.1781Node* obj = obj_node();1782LockNode* unique_lock = NULL;1783if (!box->is_simple_lock_region(&unique_lock, obj)) {1784#ifdef ASSERT1785this->log_lock_optimization(c, "eliminate_lock_INLR_2a");1786#endif1787return false;1788}1789if (unique_lock != this) {1790#ifdef ASSERT1791this->log_lock_optimization(c, "eliminate_lock_INLR_2b");1792#endif1793return false;1794}17951796// Look for external lock for the same object.1797SafePointNode* sfn = this->as_SafePoint();1798JVMState* youngest_jvms = sfn->jvms();1799int max_depth = youngest_jvms->depth();1800for (int depth = 1; depth <= max_depth; depth++) {1801JVMState* jvms = youngest_jvms->of_depth(depth);1802int num_mon = jvms->nof_monitors();1803// Loop over monitors1804for (int idx = 0; idx < num_mon; idx++) {1805Node* obj_node = sfn->monitor_obj(jvms, idx);1806BoxLockNode* box_node = sfn->monitor_box(jvms, idx)->as_BoxLock();1807if ((box_node->stack_slot() < stk_slot) && obj_node->eqv_uncast(obj)) {1808return true;1809}1810}1811}1812#ifdef ASSERT1813this->log_lock_optimization(c, "eliminate_lock_INLR_3");1814#endif1815return false;1816}18171818//=============================================================================1819uint UnlockNode::size_of() const { return sizeof(*this); }18201821//=============================================================================1822Node *UnlockNode::Ideal(PhaseGVN *phase, bool can_reshape) {18231824// perform any generic optimizations first (returns 'this' or NULL)1825Node *result = SafePointNode::Ideal(phase, can_reshape);1826if (result != NULL) return result;1827// Don't bother trying to transform a dead node1828if (in(0) && in(0)->is_top()) return NULL;18291830// Now see if we can optimize away this unlock. We don't actually1831// remove the unlocking here, we simply set the _eliminate flag which1832// prevents macro expansion from expanding the unlock. Since we don't1833// modify the graph, the value returned from this function is the1834// one computed above.1835// Escape state is defined after Parse phase.1836if (can_reshape && EliminateLocks && !is_non_esc_obj()) {1837//1838// If we are unlocking an unescaped object, the lock/unlock is unnecessary.1839//1840ConnectionGraph *cgr = phase->C->congraph();1841if (cgr != NULL && cgr->not_global_escape(obj_node())) {1842assert(!is_eliminated() || is_coarsened(), "sanity");1843// The lock could be marked eliminated by lock coarsening1844// code during first IGVN before EA. Replace coarsened flag1845// to eliminate all associated locks/unlocks.1846#ifdef ASSERT1847this->log_lock_optimization(phase->C, "eliminate_lock_set_non_esc2");1848#endif1849this->set_non_esc_obj();1850}1851}1852return result;1853}18541855const char * AbstractLockNode::kind_as_string() const {1856return is_coarsened() ? "coarsened" :1857is_nested() ? "nested" :1858is_non_esc_obj() ? "non_escaping" :1859"?";1860}18611862void AbstractLockNode::log_lock_optimization(Compile *C, const char * tag) const {1863if (C == NULL) {1864return;1865}1866CompileLog* log = C->log();1867if (log != NULL) {1868log->begin_head("%s lock='%d' compile_id='%d' class_id='%s' kind='%s'",1869tag, is_Lock(), C->compile_id(),1870is_Unlock() ? "unlock" : is_Lock() ? "lock" : "?",1871kind_as_string());1872log->stamp();1873log->end_head();1874JVMState* p = is_Unlock() ? (as_Unlock()->dbg_jvms()) : jvms();1875while (p != NULL) {1876log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));1877p = p->caller();1878}1879log->tail(tag);1880}1881}1882188318841885