Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/opto/callnode.cpp
32285 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"39#if INCLUDE_ALL_GCS40#include "gc_implementation/shenandoah/c2/shenandoahBarrierSetC2.hpp"41#endif4243// Portions of code courtesy of Clifford Click4445// Optimization - Graph Style4647//=============================================================================48uint StartNode::size_of() const { return sizeof(*this); }49uint StartNode::cmp( const Node &n ) const50{ return _domain == ((StartNode&)n)._domain; }51const Type *StartNode::bottom_type() const { return _domain; }52const Type *StartNode::Value(PhaseTransform *phase) const { return _domain; }53#ifndef PRODUCT54void StartNode::dump_spec(outputStream *st) const { st->print(" #"); _domain->dump_on(st);}55#endif5657//------------------------------Ideal------------------------------------------58Node *StartNode::Ideal(PhaseGVN *phase, bool can_reshape){59return remove_dead_region(phase, can_reshape) ? this : NULL;60}6162//------------------------------calling_convention-----------------------------63void StartNode::calling_convention( BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt ) const {64Matcher::calling_convention( sig_bt, parm_regs, argcnt, false );65}6667//------------------------------Registers--------------------------------------68const RegMask &StartNode::in_RegMask(uint) const {69return RegMask::Empty;70}7172//------------------------------match------------------------------------------73// Construct projections for incoming parameters, and their RegMask info74Node *StartNode::match( const ProjNode *proj, const Matcher *match ) {75switch (proj->_con) {76case TypeFunc::Control:77case TypeFunc::I_O:78case TypeFunc::Memory:79return new (match->C) MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);80case TypeFunc::FramePtr:81return new (match->C) MachProjNode(this,proj->_con,Matcher::c_frame_ptr_mask, Op_RegP);82case TypeFunc::ReturnAdr:83return new (match->C) MachProjNode(this,proj->_con,match->_return_addr_mask,Op_RegP);84case TypeFunc::Parms:85default: {86uint parm_num = proj->_con - TypeFunc::Parms;87const Type *t = _domain->field_at(proj->_con);88if (t->base() == Type::Half) // 2nd half of Longs and Doubles89return new (match->C) ConNode(Type::TOP);90uint ideal_reg = t->ideal_reg();91RegMask &rm = match->_calling_convention_mask[parm_num];92return new (match->C) MachProjNode(this,proj->_con,rm,ideal_reg);93}94}95return NULL;96}9798//------------------------------StartOSRNode----------------------------------99// The method start node for an on stack replacement adapter100101//------------------------------osr_domain-----------------------------102const TypeTuple *StartOSRNode::osr_domain() {103const Type **fields = TypeTuple::fields(2);104fields[TypeFunc::Parms+0] = TypeRawPtr::BOTTOM; // address of osr buffer105106return TypeTuple::make(TypeFunc::Parms+1, fields);107}108109//=============================================================================110const char * const ParmNode::names[TypeFunc::Parms+1] = {111"Control", "I_O", "Memory", "FramePtr", "ReturnAdr", "Parms"112};113114#ifndef PRODUCT115void ParmNode::dump_spec(outputStream *st) const {116if( _con < TypeFunc::Parms ) {117st->print("%s", names[_con]);118} else {119st->print("Parm%d: ",_con-TypeFunc::Parms);120// Verbose and WizardMode dump bottom_type for all nodes121if( !Verbose && !WizardMode ) bottom_type()->dump_on(st);122}123}124#endif125126uint ParmNode::ideal_reg() const {127switch( _con ) {128case TypeFunc::Control : // fall through129case TypeFunc::I_O : // fall through130case TypeFunc::Memory : return 0;131case TypeFunc::FramePtr : // fall through132case TypeFunc::ReturnAdr: return Op_RegP;133default : assert( _con > TypeFunc::Parms, "" );134// fall through135case TypeFunc::Parms : {136// Type of argument being passed137const Type *t = in(0)->as_Start()->_domain->field_at(_con);138return t->ideal_reg();139}140}141ShouldNotReachHere();142return 0;143}144145//=============================================================================146ReturnNode::ReturnNode(uint edges, Node *cntrl, Node *i_o, Node *memory, Node *frameptr, Node *retadr ) : Node(edges) {147init_req(TypeFunc::Control,cntrl);148init_req(TypeFunc::I_O,i_o);149init_req(TypeFunc::Memory,memory);150init_req(TypeFunc::FramePtr,frameptr);151init_req(TypeFunc::ReturnAdr,retadr);152}153154Node *ReturnNode::Ideal(PhaseGVN *phase, bool can_reshape){155return remove_dead_region(phase, can_reshape) ? this : NULL;156}157158const Type *ReturnNode::Value( PhaseTransform *phase ) const {159return ( phase->type(in(TypeFunc::Control)) == Type::TOP)160? Type::TOP161: Type::BOTTOM;162}163164// Do we Match on this edge index or not? No edges on return nodes165uint ReturnNode::match_edge(uint idx) const {166return 0;167}168169170#ifndef PRODUCT171void ReturnNode::dump_req(outputStream *st) const {172// Dump the required inputs, enclosed in '(' and ')'173uint i; // Exit value of loop174for (i = 0; i < req(); i++) { // For all required inputs175if (i == TypeFunc::Parms) st->print("returns");176if (in(i)) st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);177else st->print("_ ");178}179}180#endif181182//=============================================================================183RethrowNode::RethrowNode(184Node* cntrl,185Node* i_o,186Node* memory,187Node* frameptr,188Node* ret_adr,189Node* exception190) : Node(TypeFunc::Parms + 1) {191init_req(TypeFunc::Control , cntrl );192init_req(TypeFunc::I_O , i_o );193init_req(TypeFunc::Memory , memory );194init_req(TypeFunc::FramePtr , frameptr );195init_req(TypeFunc::ReturnAdr, ret_adr);196init_req(TypeFunc::Parms , exception);197}198199Node *RethrowNode::Ideal(PhaseGVN *phase, bool can_reshape){200return remove_dead_region(phase, can_reshape) ? this : NULL;201}202203const Type *RethrowNode::Value( PhaseTransform *phase ) const {204return (phase->type(in(TypeFunc::Control)) == Type::TOP)205? Type::TOP206: Type::BOTTOM;207}208209uint RethrowNode::match_edge(uint idx) const {210return 0;211}212213#ifndef PRODUCT214void RethrowNode::dump_req(outputStream *st) const {215// Dump the required inputs, enclosed in '(' and ')'216uint i; // Exit value of loop217for (i = 0; i < req(); i++) { // For all required inputs218if (i == TypeFunc::Parms) st->print("exception");219if (in(i)) st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);220else st->print("_ ");221}222}223#endif224225//=============================================================================226// Do we Match on this edge index or not? Match only target address & method227uint TailCallNode::match_edge(uint idx) const {228return TypeFunc::Parms <= idx && idx <= TypeFunc::Parms+1;229}230231//=============================================================================232// Do we Match on this edge index or not? Match only target address & oop233uint TailJumpNode::match_edge(uint idx) const {234return TypeFunc::Parms <= idx && idx <= TypeFunc::Parms+1;235}236237//=============================================================================238JVMState::JVMState(ciMethod* method, JVMState* caller) :239_method(method) {240assert(method != NULL, "must be valid call site");241_reexecute = Reexecute_Undefined;242debug_only(_bci = -99); // random garbage value243debug_only(_map = (SafePointNode*)-1);244_caller = caller;245_depth = 1 + (caller == NULL ? 0 : caller->depth());246_locoff = TypeFunc::Parms;247_stkoff = _locoff + _method->max_locals();248_monoff = _stkoff + _method->max_stack();249_scloff = _monoff;250_endoff = _monoff;251_sp = 0;252}253JVMState::JVMState(int stack_size) :254_method(NULL) {255_bci = InvocationEntryBci;256_reexecute = Reexecute_Undefined;257debug_only(_map = (SafePointNode*)-1);258_caller = NULL;259_depth = 1;260_locoff = TypeFunc::Parms;261_stkoff = _locoff;262_monoff = _stkoff + stack_size;263_scloff = _monoff;264_endoff = _monoff;265_sp = 0;266}267268//--------------------------------of_depth-------------------------------------269JVMState* JVMState::of_depth(int d) const {270const JVMState* jvmp = this;271assert(0 < d && (uint)d <= depth(), "oob");272for (int skip = depth() - d; skip > 0; skip--) {273jvmp = jvmp->caller();274}275assert(jvmp->depth() == (uint)d, "found the right one");276return (JVMState*)jvmp;277}278279//-----------------------------same_calls_as-----------------------------------280bool JVMState::same_calls_as(const JVMState* that) const {281if (this == that) return true;282if (this->depth() != that->depth()) return false;283const JVMState* p = this;284const JVMState* q = that;285for (;;) {286if (p->_method != q->_method) return false;287if (p->_method == NULL) return true; // bci is irrelevant288if (p->_bci != q->_bci) return false;289if (p->_reexecute != q->_reexecute) return false;290p = p->caller();291q = q->caller();292if (p == q) return true;293assert(p != NULL && q != NULL, "depth check ensures we don't run off end");294}295}296297//------------------------------debug_start------------------------------------298uint JVMState::debug_start() const {299debug_only(JVMState* jvmroot = of_depth(1));300assert(jvmroot->locoff() <= this->locoff(), "youngest JVMState must be last");301return of_depth(1)->locoff();302}303304//-------------------------------debug_end-------------------------------------305uint JVMState::debug_end() const {306debug_only(JVMState* jvmroot = of_depth(1));307assert(jvmroot->endoff() <= this->endoff(), "youngest JVMState must be last");308return endoff();309}310311//------------------------------debug_depth------------------------------------312uint JVMState::debug_depth() const {313uint total = 0;314for (const JVMState* jvmp = this; jvmp != NULL; jvmp = jvmp->caller()) {315total += jvmp->debug_size();316}317return total;318}319320#ifndef PRODUCT321322//------------------------------format_helper----------------------------------323// Given an allocation (a Chaitin object) and a Node decide if the Node carries324// any defined value or not. If it does, print out the register or constant.325static void format_helper( PhaseRegAlloc *regalloc, outputStream* st, Node *n, const char *msg, uint i, GrowableArray<SafePointScalarObjectNode*> *scobjs ) {326if (n == NULL) { st->print(" NULL"); return; }327if (n->is_SafePointScalarObject()) {328// Scalar replacement.329SafePointScalarObjectNode* spobj = n->as_SafePointScalarObject();330scobjs->append_if_missing(spobj);331int sco_n = scobjs->find(spobj);332assert(sco_n >= 0, "");333st->print(" %s%d]=#ScObj" INT32_FORMAT, msg, i, sco_n);334return;335}336if (regalloc->node_regs_max_index() > 0 &&337OptoReg::is_valid(regalloc->get_reg_first(n))) { // Check for undefined338char buf[50];339regalloc->dump_register(n,buf);340st->print(" %s%d]=%s",msg,i,buf);341} else { // No register, but might be constant342const Type *t = n->bottom_type();343switch (t->base()) {344case Type::Int:345st->print(" %s%d]=#" INT32_FORMAT,msg,i,t->is_int()->get_con());346break;347case Type::AnyPtr:348assert( t == TypePtr::NULL_PTR || n->in_dump(), "" );349st->print(" %s%d]=#NULL",msg,i);350break;351case Type::AryPtr:352case Type::InstPtr:353st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->isa_oopptr()->const_oop()));354break;355case Type::KlassPtr:356st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_klassptr()->klass()));357break;358case Type::MetadataPtr:359st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_metadataptr()->metadata()));360break;361case Type::NarrowOop:362st->print(" %s%d]=#Ptr" INTPTR_FORMAT,msg,i,p2i(t->make_ptr()->isa_oopptr()->const_oop()));363break;364case Type::RawPtr:365st->print(" %s%d]=#Raw" INTPTR_FORMAT,msg,i,p2i(t->is_rawptr()));366break;367case Type::DoubleCon:368st->print(" %s%d]=#%fD",msg,i,t->is_double_constant()->_d);369break;370case Type::FloatCon:371st->print(" %s%d]=#%fF",msg,i,t->is_float_constant()->_f);372break;373case Type::Long:374st->print(" %s%d]=#" INT64_FORMAT,msg,i,(int64_t)(t->is_long()->get_con()));375break;376case Type::Half:377case Type::Top:378st->print(" %s%d]=_",msg,i);379break;380default: ShouldNotReachHere();381}382}383}384385//------------------------------format-----------------------------------------386void JVMState::format(PhaseRegAlloc *regalloc, const Node *n, outputStream* st) const {387st->print(" #");388if (_method) {389_method->print_short_name(st);390st->print(" @ bci:%d ",_bci);391} else {392st->print_cr(" runtime stub ");393return;394}395if (n->is_MachSafePoint()) {396GrowableArray<SafePointScalarObjectNode*> scobjs;397MachSafePointNode *mcall = n->as_MachSafePoint();398uint i;399// Print locals400for (i = 0; i < (uint)loc_size(); i++)401format_helper(regalloc, st, mcall->local(this, i), "L[", i, &scobjs);402// Print stack403for (i = 0; i < (uint)stk_size(); i++) {404if ((uint)(_stkoff + i) >= mcall->len())405st->print(" oob ");406else407format_helper(regalloc, st, mcall->stack(this, i), "STK[", i, &scobjs);408}409for (i = 0; (int)i < nof_monitors(); i++) {410Node *box = mcall->monitor_box(this, i);411Node *obj = mcall->monitor_obj(this, i);412if (regalloc->node_regs_max_index() > 0 &&413OptoReg::is_valid(regalloc->get_reg_first(box))) {414box = BoxLockNode::box_node(box);415format_helper(regalloc, st, box, "MON-BOX[", i, &scobjs);416} else {417OptoReg::Name box_reg = BoxLockNode::reg(box);418st->print(" MON-BOX%d=%s+%d",419i,420OptoReg::regname(OptoReg::c_frame_pointer),421regalloc->reg2offset(box_reg));422}423const char* obj_msg = "MON-OBJ[";424if (EliminateLocks) {425if (BoxLockNode::box_node(box)->is_eliminated())426obj_msg = "MON-OBJ(LOCK ELIMINATED)[";427}428format_helper(regalloc, st, obj, obj_msg, i, &scobjs);429}430431for (i = 0; i < (uint)scobjs.length(); i++) {432// Scalar replaced objects.433st->cr();434st->print(" # ScObj" INT32_FORMAT " ", i);435SafePointScalarObjectNode* spobj = scobjs.at(i);436ciKlass* cik = spobj->bottom_type()->is_oopptr()->klass();437assert(cik->is_instance_klass() ||438cik->is_array_klass(), "Not supported allocation.");439ciInstanceKlass *iklass = NULL;440if (cik->is_instance_klass()) {441cik->print_name_on(st);442iklass = cik->as_instance_klass();443} else if (cik->is_type_array_klass()) {444cik->as_array_klass()->base_element_type()->print_name_on(st);445st->print("[%d]", spobj->n_fields());446} else if (cik->is_obj_array_klass()) {447ciKlass* cie = cik->as_obj_array_klass()->base_element_klass();448if (cie->is_instance_klass()) {449cie->print_name_on(st);450} else if (cie->is_type_array_klass()) {451cie->as_array_klass()->base_element_type()->print_name_on(st);452} else {453ShouldNotReachHere();454}455st->print("[%d]", spobj->n_fields());456int ndim = cik->as_array_klass()->dimension() - 1;457while (ndim-- > 0) {458st->print("[]");459}460}461st->print("={");462uint nf = spobj->n_fields();463if (nf > 0) {464uint first_ind = spobj->first_index(mcall->jvms());465Node* fld_node = mcall->in(first_ind);466ciField* cifield;467if (iklass != NULL) {468st->print(" [");469cifield = iklass->nonstatic_field_at(0);470cifield->print_name_on(st);471format_helper(regalloc, st, fld_node, ":", 0, &scobjs);472} else {473format_helper(regalloc, st, fld_node, "[", 0, &scobjs);474}475for (uint j = 1; j < nf; j++) {476fld_node = mcall->in(first_ind+j);477if (iklass != NULL) {478st->print(", [");479cifield = iklass->nonstatic_field_at(j);480cifield->print_name_on(st);481format_helper(regalloc, st, fld_node, ":", j, &scobjs);482} else {483format_helper(regalloc, st, fld_node, ", [", j, &scobjs);484}485}486}487st->print(" }");488}489}490st->cr();491if (caller() != NULL) caller()->format(regalloc, n, st);492}493494495void JVMState::dump_spec(outputStream *st) const {496if (_method != NULL) {497bool printed = false;498if (!Verbose) {499// The JVMS dumps make really, really long lines.500// Take out the most boring parts, which are the package prefixes.501char buf[500];502stringStream namest(buf, sizeof(buf));503_method->print_short_name(&namest);504if (namest.count() < sizeof(buf)) {505const char* name = namest.base();506if (name[0] == ' ') ++name;507const char* endcn = strchr(name, ':'); // end of class name508if (endcn == NULL) endcn = strchr(name, '(');509if (endcn == NULL) endcn = name + strlen(name);510while (endcn > name && endcn[-1] != '.' && endcn[-1] != '/')511--endcn;512st->print(" %s", endcn);513printed = true;514}515}516if (!printed)517_method->print_short_name(st);518st->print(" @ bci:%d",_bci);519if(_reexecute == Reexecute_True)520st->print(" reexecute");521} else {522st->print(" runtime stub");523}524if (caller() != NULL) caller()->dump_spec(st);525}526527528void JVMState::dump_on(outputStream* st) const {529bool print_map = _map && !((uintptr_t)_map & 1) &&530((caller() == NULL) || (caller()->map() != _map));531if (print_map) {532if (_map->len() > _map->req()) { // _map->has_exceptions()533Node* ex = _map->in(_map->req()); // _map->next_exception()534// skip the first one; it's already being printed535while (ex != NULL && ex->len() > ex->req()) {536ex = ex->in(ex->req()); // ex->next_exception()537ex->dump(1);538}539}540_map->dump(Verbose ? 2 : 1);541}542if (caller() != NULL) {543caller()->dump_on(st);544}545st->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=",546depth(), locoff(), stkoff(), argoff(), monoff(), scloff(), endoff(), monitor_depth(), sp(), bci(), should_reexecute()?"true":"false");547if (_method == NULL) {548st->print_cr("(none)");549} else {550_method->print_name(st);551st->cr();552if (bci() >= 0 && bci() < _method->code_size()) {553st->print(" bc: ");554_method->print_codes_on(bci(), bci()+1, st);555}556}557}558559// Extra way to dump a jvms from the debugger,560// to avoid a bug with C++ member function calls.561void dump_jvms(JVMState* jvms) {562jvms->dump();563}564#endif565566//--------------------------clone_shallow--------------------------------------567JVMState* JVMState::clone_shallow(Compile* C) const {568JVMState* n = has_method() ? new (C) JVMState(_method, _caller) : new (C) JVMState(0);569n->set_bci(_bci);570n->_reexecute = _reexecute;571n->set_locoff(_locoff);572n->set_stkoff(_stkoff);573n->set_monoff(_monoff);574n->set_scloff(_scloff);575n->set_endoff(_endoff);576n->set_sp(_sp);577n->set_map(_map);578return n;579}580581//---------------------------clone_deep----------------------------------------582JVMState* JVMState::clone_deep(Compile* C) const {583JVMState* n = clone_shallow(C);584for (JVMState* p = n; p->_caller != NULL; p = p->_caller) {585p->_caller = p->_caller->clone_shallow(C);586}587assert(n->depth() == depth(), "sanity");588assert(n->debug_depth() == debug_depth(), "sanity");589return n;590}591592/**593* Reset map for all callers594*/595void JVMState::set_map_deep(SafePointNode* map) {596for (JVMState* p = this; p->_caller != NULL; p = p->_caller) {597p->set_map(map);598}599}600601// Adapt offsets in in-array after adding or removing an edge.602// Prerequisite is that the JVMState is used by only one node.603void JVMState::adapt_position(int delta) {604for (JVMState* jvms = this; jvms != NULL; jvms = jvms->caller()) {605jvms->set_locoff(jvms->locoff() + delta);606jvms->set_stkoff(jvms->stkoff() + delta);607jvms->set_monoff(jvms->monoff() + delta);608jvms->set_scloff(jvms->scloff() + delta);609jvms->set_endoff(jvms->endoff() + delta);610}611}612613// Mirror the stack size calculation in the deopt code614// How much stack space would we need at this point in the program in615// case of deoptimization?616int JVMState::interpreter_frame_size() const {617const JVMState* jvms = this;618int size = 0;619int callee_parameters = 0;620int callee_locals = 0;621int extra_args = method()->max_stack() - stk_size();622623while (jvms != NULL) {624int locks = jvms->nof_monitors();625int temps = jvms->stk_size();626bool is_top_frame = (jvms == this);627ciMethod* method = jvms->method();628629int frame_size = BytesPerWord * Interpreter::size_activation(method->max_stack(),630temps + callee_parameters,631extra_args,632locks,633callee_parameters,634callee_locals,635is_top_frame);636size += frame_size;637638callee_parameters = method->size_of_parameters();639callee_locals = method->max_locals();640extra_args = 0;641jvms = jvms->caller();642}643return size + Deoptimization::last_frame_adjust(0, callee_locals) * BytesPerWord;644}645646//=============================================================================647uint CallNode::cmp( const Node &n ) const648{ return _tf == ((CallNode&)n)._tf && _jvms == ((CallNode&)n)._jvms; }649#ifndef PRODUCT650void CallNode::dump_req(outputStream *st) const {651// Dump the required inputs, enclosed in '(' and ')'652uint i; // Exit value of loop653for (i = 0; i < req(); i++) { // For all required inputs654if (i == TypeFunc::Parms) st->print("(");655if (in(i)) st->print("%c%d ", Compile::current()->node_arena()->contains(in(i)) ? ' ' : 'o', in(i)->_idx);656else st->print("_ ");657}658st->print(")");659}660661void CallNode::dump_spec(outputStream *st) const {662st->print(" ");663tf()->dump_on(st);664if (_cnt != COUNT_UNKNOWN) st->print(" C=%f",_cnt);665if (jvms() != NULL) jvms()->dump_spec(st);666}667#endif668669const Type *CallNode::bottom_type() const { return tf()->range(); }670const Type *CallNode::Value(PhaseTransform *phase) const {671if (phase->type(in(0)) == Type::TOP) return Type::TOP;672return tf()->range();673}674675//------------------------------calling_convention-----------------------------676void CallNode::calling_convention( BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt ) const {677// Use the standard compiler calling convention678Matcher::calling_convention( sig_bt, parm_regs, argcnt, true );679}680681682//------------------------------match------------------------------------------683// Construct projections for control, I/O, memory-fields, ..., and684// return result(s) along with their RegMask info685Node *CallNode::match( const ProjNode *proj, const Matcher *match ) {686switch (proj->_con) {687case TypeFunc::Control:688case TypeFunc::I_O:689case TypeFunc::Memory:690return new (match->C) MachProjNode(this,proj->_con,RegMask::Empty,MachProjNode::unmatched_proj);691692case TypeFunc::Parms+1: // For LONG & DOUBLE returns693assert(tf()->_range->field_at(TypeFunc::Parms+1) == Type::HALF, "");694// 2nd half of doubles and longs695return new (match->C) MachProjNode(this,proj->_con, RegMask::Empty, (uint)OptoReg::Bad);696697case TypeFunc::Parms: { // Normal returns698uint ideal_reg = tf()->range()->field_at(TypeFunc::Parms)->ideal_reg();699OptoRegPair regs = is_CallRuntime()700? match->c_return_value(ideal_reg,true) // Calls into C runtime701: match-> return_value(ideal_reg,true); // Calls into compiled Java code702RegMask rm = RegMask(regs.first());703if( OptoReg::is_valid(regs.second()) )704rm.Insert( regs.second() );705return new (match->C) MachProjNode(this,proj->_con,rm,ideal_reg);706}707708case TypeFunc::ReturnAdr:709case TypeFunc::FramePtr:710default:711ShouldNotReachHere();712}713return NULL;714}715716// Do we Match on this edge index or not? Match no edges717uint CallNode::match_edge(uint idx) const {718return 0;719}720721//722// Determine whether the call could modify the field of the specified723// instance at the specified offset.724//725bool CallNode::may_modify(const TypeOopPtr *t_oop, PhaseTransform *phase) {726assert((t_oop != NULL), "sanity");727if (t_oop->is_known_instance()) {728// The instance_id is set only for scalar-replaceable allocations which729// are not passed as arguments according to Escape Analysis.730return false;731}732if (t_oop->is_ptr_to_boxed_value()) {733ciKlass* boxing_klass = t_oop->klass();734if (is_CallStaticJava() && as_CallStaticJava()->is_boxing_method()) {735// Skip unrelated boxing methods.736Node* proj = proj_out(TypeFunc::Parms);737if ((proj == NULL) || (phase->type(proj)->is_instptr()->klass() != boxing_klass)) {738return false;739}740}741if (is_CallJava() && as_CallJava()->method() != NULL) {742ciMethod* meth = as_CallJava()->method();743if (meth->is_accessor()) {744return false;745}746// May modify (by reflection) if an boxing object is passed747// as argument or returned.748Node* proj = returns_pointer() ? proj_out(TypeFunc::Parms) : NULL;749if (proj != NULL) {750const TypeInstPtr* inst_t = phase->type(proj)->isa_instptr();751if ((inst_t != NULL) && (!inst_t->klass_is_exact() ||752(inst_t->klass() == boxing_klass))) {753return true;754}755}756const TypeTuple* d = tf()->domain();757for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {758const TypeInstPtr* inst_t = d->field_at(i)->isa_instptr();759if ((inst_t != NULL) && (!inst_t->klass_is_exact() ||760(inst_t->klass() == boxing_klass))) {761return true;762}763}764return false;765}766}767return true;768}769770// Does this call have a direct reference to n other than debug information?771bool CallNode::has_non_debug_use(Node *n) {772const TypeTuple * d = tf()->domain();773for (uint i = TypeFunc::Parms; i < d->cnt(); i++) {774Node *arg = in(i);775if (arg == n) {776return true;777}778}779return false;780}781782// Returns the unique CheckCastPP of a call783// or 'this' if there are several CheckCastPP or unexpected uses784// or returns NULL if there is no one.785Node *CallNode::result_cast() {786Node *cast = NULL;787788Node *p = proj_out(TypeFunc::Parms);789if (p == NULL)790return NULL;791792for (DUIterator_Fast imax, i = p->fast_outs(imax); i < imax; i++) {793Node *use = p->fast_out(i);794if (use->is_CheckCastPP()) {795if (cast != NULL) {796return this; // more than 1 CheckCastPP797}798cast = use;799} else if (!use->is_Initialize() &&800!use->is_AddP()) {801// Expected uses are restricted to a CheckCastPP, an Initialize802// node, and AddP nodes. If we encounter any other use (a Phi803// node can be seen in rare cases) return this to prevent804// incorrect optimizations.805return this;806}807}808return cast;809}810811812void CallNode::extract_projections(CallProjections* projs, bool separate_io_proj, bool do_asserts) {813projs->fallthrough_proj = NULL;814projs->fallthrough_catchproj = NULL;815projs->fallthrough_ioproj = NULL;816projs->catchall_ioproj = NULL;817projs->catchall_catchproj = NULL;818projs->fallthrough_memproj = NULL;819projs->catchall_memproj = NULL;820projs->resproj = NULL;821projs->exobj = NULL;822823for (DUIterator_Fast imax, i = fast_outs(imax); i < imax; i++) {824ProjNode *pn = fast_out(i)->as_Proj();825if (pn->outcnt() == 0) continue;826switch (pn->_con) {827case TypeFunc::Control:828{829// For Control (fallthrough) and I_O (catch_all_index) we have CatchProj -> Catch -> Proj830projs->fallthrough_proj = pn;831DUIterator_Fast jmax, j = pn->fast_outs(jmax);832const Node *cn = pn->fast_out(j);833if (cn->is_Catch()) {834ProjNode *cpn = NULL;835for (DUIterator_Fast kmax, k = cn->fast_outs(kmax); k < kmax; k++) {836cpn = cn->fast_out(k)->as_Proj();837assert(cpn->is_CatchProj(), "must be a CatchProjNode");838if (cpn->_con == CatchProjNode::fall_through_index)839projs->fallthrough_catchproj = cpn;840else {841assert(cpn->_con == CatchProjNode::catch_all_index, "must be correct index.");842projs->catchall_catchproj = cpn;843}844}845}846break;847}848case TypeFunc::I_O:849if (pn->_is_io_use)850projs->catchall_ioproj = pn;851else852projs->fallthrough_ioproj = pn;853for (DUIterator j = pn->outs(); pn->has_out(j); j++) {854Node* e = pn->out(j);855if (e->Opcode() == Op_CreateEx && e->in(0)->is_CatchProj() && e->outcnt() > 0) {856assert(projs->exobj == NULL, "only one");857projs->exobj = e;858}859}860break;861case TypeFunc::Memory:862if (pn->_is_io_use)863projs->catchall_memproj = pn;864else865projs->fallthrough_memproj = pn;866break;867case TypeFunc::Parms:868projs->resproj = pn;869break;870default:871assert(false, "unexpected projection from allocation node.");872}873}874875// The resproj may not exist because the result could be ignored876// and the exception object may not exist if an exception handler877// swallows the exception but all the other must exist and be found.878assert(projs->fallthrough_proj != NULL, "must be found");879do_asserts = do_asserts && !Compile::current()->inlining_incrementally();880assert(!do_asserts || projs->fallthrough_catchproj != NULL, "must be found");881assert(!do_asserts || projs->fallthrough_memproj != NULL, "must be found");882assert(!do_asserts || projs->fallthrough_ioproj != NULL, "must be found");883assert(!do_asserts || projs->catchall_catchproj != NULL, "must be found");884if (separate_io_proj) {885assert(!do_asserts || projs->catchall_memproj != NULL, "must be found");886assert(!do_asserts || projs->catchall_ioproj != NULL, "must be found");887}888}889890Node *CallNode::Ideal(PhaseGVN *phase, bool can_reshape) {891CallGenerator* cg = generator();892if (can_reshape && cg != NULL && cg->is_mh_late_inline() && !cg->already_attempted()) {893// Check whether this MH handle call becomes a candidate for inlining894ciMethod* callee = cg->method();895vmIntrinsics::ID iid = callee->intrinsic_id();896if (iid == vmIntrinsics::_invokeBasic) {897if (in(TypeFunc::Parms)->Opcode() == Op_ConP) {898phase->C->prepend_late_inline(cg);899set_generator(NULL);900}901} else {902assert(callee->has_member_arg(), "wrong type of call?");903if (in(TypeFunc::Parms + callee->arg_size() - 1)->Opcode() == Op_ConP) {904phase->C->prepend_late_inline(cg);905set_generator(NULL);906}907}908}909return SafePointNode::Ideal(phase, can_reshape);910}911912//=============================================================================913uint CallJavaNode::size_of() const { return sizeof(*this); }914uint CallJavaNode::cmp( const Node &n ) const {915CallJavaNode &call = (CallJavaNode&)n;916return CallNode::cmp(call) && _method == call._method;917}918#ifndef PRODUCT919void CallJavaNode::dump_spec(outputStream *st) const {920if( _method ) _method->print_short_name(st);921CallNode::dump_spec(st);922}923#endif924925//=============================================================================926uint CallStaticJavaNode::size_of() const { return sizeof(*this); }927uint CallStaticJavaNode::cmp( const Node &n ) const {928CallStaticJavaNode &call = (CallStaticJavaNode&)n;929return CallJavaNode::cmp(call);930}931932//----------------------------uncommon_trap_request----------------------------933// If this is an uncommon trap, return the request code, else zero.934int CallStaticJavaNode::uncommon_trap_request() const {935if (_name != NULL && !strcmp(_name, "uncommon_trap")) {936return extract_uncommon_trap_request(this);937}938return 0;939}940int CallStaticJavaNode::extract_uncommon_trap_request(const Node* call) {941#ifndef PRODUCT942if (!(call->req() > TypeFunc::Parms &&943call->in(TypeFunc::Parms) != NULL &&944call->in(TypeFunc::Parms)->is_Con())) {945assert(in_dump() != 0, "OK if dumping");946tty->print("[bad uncommon trap]");947return 0;948}949#endif950return call->in(TypeFunc::Parms)->bottom_type()->is_int()->get_con();951}952953#ifndef PRODUCT954void CallStaticJavaNode::dump_spec(outputStream *st) const {955st->print("# Static ");956if (_name != NULL) {957st->print("%s", _name);958int trap_req = uncommon_trap_request();959if (trap_req != 0) {960char buf[100];961st->print("(%s)",962Deoptimization::format_trap_request(buf, sizeof(buf),963trap_req));964}965st->print(" ");966}967CallJavaNode::dump_spec(st);968}969#endif970971//=============================================================================972uint CallDynamicJavaNode::size_of() const { return sizeof(*this); }973uint CallDynamicJavaNode::cmp( const Node &n ) const {974CallDynamicJavaNode &call = (CallDynamicJavaNode&)n;975return CallJavaNode::cmp(call);976}977#ifndef PRODUCT978void CallDynamicJavaNode::dump_spec(outputStream *st) const {979st->print("# Dynamic ");980CallJavaNode::dump_spec(st);981}982#endif983984//=============================================================================985uint CallRuntimeNode::size_of() const { return sizeof(*this); }986uint CallRuntimeNode::cmp( const Node &n ) const {987CallRuntimeNode &call = (CallRuntimeNode&)n;988return CallNode::cmp(call) && !strcmp(_name,call._name);989}990#ifndef PRODUCT991void CallRuntimeNode::dump_spec(outputStream *st) const {992st->print("# ");993st->print("%s", _name);994CallNode::dump_spec(st);995}996#endif997998//------------------------------calling_convention-----------------------------999void CallRuntimeNode::calling_convention( BasicType* sig_bt, VMRegPair *parm_regs, uint argcnt ) const {1000Matcher::c_calling_convention( sig_bt, parm_regs, argcnt );1001}10021003bool CallRuntimeNode::is_call_to_arraycopystub() const {1004if (_name != NULL && strstr(_name, "arraycopy") != 0) {1005return true;1006}1007return false;1008}10091010//=============================================================================1011//------------------------------calling_convention-----------------------------101210131014//=============================================================================1015#ifndef PRODUCT1016void CallLeafNode::dump_spec(outputStream *st) const {1017st->print("# ");1018st->print("%s", _name);1019CallNode::dump_spec(st);1020}1021#endif10221023Node *CallLeafNode::Ideal(PhaseGVN *phase, bool can_reshape) {1024if (UseShenandoahGC && is_g1_wb_pre_call()) {1025uint cnt = OptoRuntime::g1_wb_pre_Type()->domain()->cnt();1026if (req() > cnt) {1027Node* addp = in(cnt);1028if (has_only_g1_wb_pre_uses(addp)) {1029del_req(cnt);1030if (can_reshape) {1031phase->is_IterGVN()->_worklist.push(addp);1032}1033return this;1034}1035}1036}10371038return CallNode::Ideal(phase, can_reshape);1039}10401041bool CallLeafNode::has_only_g1_wb_pre_uses(Node* n) {1042if (UseShenandoahGC) {1043return false;1044}1045for (DUIterator_Fast imax, i = n->fast_outs(imax); i < imax; i++) {1046Node* u = n->fast_out(i);1047if (!u->is_g1_wb_pre_call()) {1048return false;1049}1050}1051return n->outcnt() > 0;1052}10531054//=============================================================================10551056void SafePointNode::set_local(JVMState* jvms, uint idx, Node *c) {1057assert(verify_jvms(jvms), "jvms must match");1058int loc = jvms->locoff() + idx;1059if (in(loc)->is_top() && idx > 0 && !c->is_top() ) {1060// If current local idx is top then local idx - 1 could1061// be a long/double that needs to be killed since top could1062// represent the 2nd half ofthe long/double.1063uint ideal = in(loc -1)->ideal_reg();1064if (ideal == Op_RegD || ideal == Op_RegL) {1065// set other (low index) half to top1066set_req(loc - 1, in(loc));1067}1068}1069set_req(loc, c);1070}10711072uint SafePointNode::size_of() const { return sizeof(*this); }1073uint SafePointNode::cmp( const Node &n ) const {1074return (&n == this); // Always fail except on self1075}10761077//-------------------------set_next_exception----------------------------------1078void SafePointNode::set_next_exception(SafePointNode* n) {1079assert(n == NULL || n->Opcode() == Op_SafePoint, "correct value for next_exception");1080if (len() == req()) {1081if (n != NULL) add_prec(n);1082} else {1083set_prec(req(), n);1084}1085}108610871088//----------------------------next_exception-----------------------------------1089SafePointNode* SafePointNode::next_exception() const {1090if (len() == req()) {1091return NULL;1092} else {1093Node* n = in(req());1094assert(n == NULL || n->Opcode() == Op_SafePoint, "no other uses of prec edges");1095return (SafePointNode*) n;1096}1097}109810991100//------------------------------Ideal------------------------------------------1101// Skip over any collapsed Regions1102Node *SafePointNode::Ideal(PhaseGVN *phase, bool can_reshape) {1103return remove_dead_region(phase, can_reshape) ? this : NULL;1104}11051106//------------------------------Identity---------------------------------------1107// Remove obviously duplicate safepoints1108Node *SafePointNode::Identity( PhaseTransform *phase ) {11091110// If you have back to back safepoints, remove one1111if( in(TypeFunc::Control)->is_SafePoint() )1112return in(TypeFunc::Control);11131114if( in(0)->is_Proj() ) {1115Node *n0 = in(0)->in(0);1116// Check if he is a call projection (except Leaf Call)1117if( n0->is_Catch() ) {1118n0 = n0->in(0)->in(0);1119assert( n0->is_Call(), "expect a call here" );1120}1121if( n0->is_Call() && n0->as_Call()->guaranteed_safepoint() ) {1122// Useless Safepoint, so remove it1123return in(TypeFunc::Control);1124}1125}11261127return this;1128}11291130//------------------------------Value------------------------------------------1131const Type *SafePointNode::Value( PhaseTransform *phase ) const {1132if( phase->type(in(0)) == Type::TOP ) return Type::TOP;1133if( phase->eqv( in(0), this ) ) return Type::TOP; // Dead infinite loop1134return Type::CONTROL;1135}11361137#ifndef PRODUCT1138void SafePointNode::dump_spec(outputStream *st) const {1139st->print(" SafePoint ");1140_replaced_nodes.dump(st);1141}1142#endif11431144const RegMask &SafePointNode::in_RegMask(uint idx) const {1145if( idx < TypeFunc::Parms ) return RegMask::Empty;1146// Values outside the domain represent debug info1147return *(Compile::current()->matcher()->idealreg2debugmask[in(idx)->ideal_reg()]);1148}1149const RegMask &SafePointNode::out_RegMask() const {1150return RegMask::Empty;1151}115211531154void SafePointNode::grow_stack(JVMState* jvms, uint grow_by) {1155assert((int)grow_by > 0, "sanity");1156int monoff = jvms->monoff();1157int scloff = jvms->scloff();1158int endoff = jvms->endoff();1159assert(endoff == (int)req(), "no other states or debug info after me");1160Node* top = Compile::current()->top();1161for (uint i = 0; i < grow_by; i++) {1162ins_req(monoff, top);1163}1164jvms->set_monoff(monoff + grow_by);1165jvms->set_scloff(scloff + grow_by);1166jvms->set_endoff(endoff + grow_by);1167}11681169void SafePointNode::push_monitor(const FastLockNode *lock) {1170// Add a LockNode, which points to both the original BoxLockNode (the1171// stack space for the monitor) and the Object being locked.1172const int MonitorEdges = 2;1173assert(JVMState::logMonitorEdges == exact_log2(MonitorEdges), "correct MonitorEdges");1174assert(req() == jvms()->endoff(), "correct sizing");1175int nextmon = jvms()->scloff();1176if (GenerateSynchronizationCode) {1177ins_req(nextmon, lock->box_node());1178ins_req(nextmon+1, lock->obj_node());1179} else {1180Node* top = Compile::current()->top();1181ins_req(nextmon, top);1182ins_req(nextmon, top);1183}1184jvms()->set_scloff(nextmon + MonitorEdges);1185jvms()->set_endoff(req());1186}11871188void SafePointNode::pop_monitor() {1189// Delete last monitor from debug info1190debug_only(int num_before_pop = jvms()->nof_monitors());1191const int MonitorEdges = 2;1192assert(JVMState::logMonitorEdges == exact_log2(MonitorEdges), "correct MonitorEdges");1193int scloff = jvms()->scloff();1194int endoff = jvms()->endoff();1195int new_scloff = scloff - MonitorEdges;1196int new_endoff = endoff - MonitorEdges;1197jvms()->set_scloff(new_scloff);1198jvms()->set_endoff(new_endoff);1199while (scloff > new_scloff) del_req_ordered(--scloff);1200assert(jvms()->nof_monitors() == num_before_pop-1, "");1201}12021203Node *SafePointNode::peek_monitor_box() const {1204int mon = jvms()->nof_monitors() - 1;1205assert(mon >= 0, "most have a monitor");1206return monitor_box(jvms(), mon);1207}12081209Node *SafePointNode::peek_monitor_obj() const {1210int mon = jvms()->nof_monitors() - 1;1211assert(mon >= 0, "most have a monitor");1212return monitor_obj(jvms(), mon);1213}12141215// Do we Match on this edge index or not? Match no edges1216uint SafePointNode::match_edge(uint idx) const {1217if( !needs_polling_address_input() )1218return 0;12191220return (TypeFunc::Parms == idx);1221}12221223void SafePointNode::disconnect_from_root(PhaseIterGVN *igvn) {1224assert(Opcode() == Op_SafePoint, "only value for safepoint in loops");1225int nb = igvn->C->root()->find_prec_edge(this);1226if (nb != -1) {1227igvn->C->root()->rm_prec(nb);1228}1229}12301231//============== SafePointScalarObjectNode ==============12321233SafePointScalarObjectNode::SafePointScalarObjectNode(const TypeOopPtr* tp,1234#ifdef ASSERT1235AllocateNode* alloc,1236#endif1237uint first_index,1238uint n_fields) :1239TypeNode(tp, 1), // 1 control input -- seems required. Get from root.1240#ifdef ASSERT1241_alloc(alloc),1242#endif1243_first_index(first_index),1244_n_fields(n_fields)1245{1246init_class_id(Class_SafePointScalarObject);1247}12481249// Do not allow value-numbering for SafePointScalarObject node.1250uint SafePointScalarObjectNode::hash() const { return NO_HASH; }1251uint SafePointScalarObjectNode::cmp( const Node &n ) const {1252return (&n == this); // Always fail except on self1253}12541255uint SafePointScalarObjectNode::ideal_reg() const {1256return 0; // No matching to machine instruction1257}12581259const RegMask &SafePointScalarObjectNode::in_RegMask(uint idx) const {1260return *(Compile::current()->matcher()->idealreg2debugmask[in(idx)->ideal_reg()]);1261}12621263const RegMask &SafePointScalarObjectNode::out_RegMask() const {1264return RegMask::Empty;1265}12661267uint SafePointScalarObjectNode::match_edge(uint idx) const {1268return 0;1269}12701271SafePointScalarObjectNode*1272SafePointScalarObjectNode::clone(Dict* sosn_map) const {1273void* cached = (*sosn_map)[(void*)this];1274if (cached != NULL) {1275return (SafePointScalarObjectNode*)cached;1276}1277SafePointScalarObjectNode* res = (SafePointScalarObjectNode*)Node::clone();1278sosn_map->Insert((void*)this, (void*)res);1279return res;1280}128112821283#ifndef PRODUCT1284void SafePointScalarObjectNode::dump_spec(outputStream *st) const {1285st->print(" # fields@[%d..%d]", first_index(),1286first_index() + n_fields() - 1);1287}12881289#endif12901291//=============================================================================1292uint AllocateNode::size_of() const { return sizeof(*this); }12931294AllocateNode::AllocateNode(Compile* C, const TypeFunc *atype,1295Node *ctrl, Node *mem, Node *abio,1296Node *size, Node *klass_node, Node *initial_test)1297: CallNode(atype, NULL, TypeRawPtr::BOTTOM)1298{1299init_class_id(Class_Allocate);1300init_flags(Flag_is_macro);1301_is_scalar_replaceable = false;1302_is_non_escaping = false;1303Node *topnode = C->top();13041305init_req( TypeFunc::Control , ctrl );1306init_req( TypeFunc::I_O , abio );1307init_req( TypeFunc::Memory , mem );1308init_req( TypeFunc::ReturnAdr, topnode );1309init_req( TypeFunc::FramePtr , topnode );1310init_req( AllocSize , size);1311init_req( KlassNode , klass_node);1312init_req( InitialTest , initial_test);1313init_req( ALength , topnode);1314C->add_macro_node(this);1315}13161317//=============================================================================1318Node* AllocateArrayNode::Ideal(PhaseGVN *phase, bool can_reshape) {1319if (remove_dead_region(phase, can_reshape)) return this;1320// Don't bother trying to transform a dead node1321if (in(0) && in(0)->is_top()) return NULL;13221323const Type* type = phase->type(Ideal_length());1324if (type->isa_int() && type->is_int()->_hi < 0) {1325if (can_reshape) {1326PhaseIterGVN *igvn = phase->is_IterGVN();1327// Unreachable fall through path (negative array length),1328// the allocation can only throw so disconnect it.1329Node* proj = proj_out(TypeFunc::Control);1330Node* catchproj = NULL;1331if (proj != NULL) {1332for (DUIterator_Fast imax, i = proj->fast_outs(imax); i < imax; i++) {1333Node *cn = proj->fast_out(i);1334if (cn->is_Catch()) {1335catchproj = cn->as_Multi()->proj_out(CatchProjNode::fall_through_index);1336break;1337}1338}1339}1340if (catchproj != NULL && catchproj->outcnt() > 0 &&1341(catchproj->outcnt() > 1 ||1342catchproj->unique_out()->Opcode() != Op_Halt)) {1343assert(catchproj->is_CatchProj(), "must be a CatchProjNode");1344Node* nproj = catchproj->clone();1345igvn->register_new_node_with_optimizer(nproj);13461347Node *frame = new (phase->C) ParmNode( phase->C->start(), TypeFunc::FramePtr );1348frame = phase->transform(frame);1349// Halt & Catch Fire1350Node *halt = new (phase->C) HaltNode( nproj, frame );1351phase->C->root()->add_req(halt);1352phase->transform(halt);13531354igvn->replace_node(catchproj, phase->C->top());1355return this;1356}1357} else {1358// Can't correct it during regular GVN so register for IGVN1359phase->C->record_for_igvn(this);1360}1361}1362return NULL;1363}13641365// Retrieve the length from the AllocateArrayNode. Narrow the type with a1366// CastII, if appropriate. If we are not allowed to create new nodes, and1367// a CastII is appropriate, return NULL.1368Node *AllocateArrayNode::make_ideal_length(const TypeOopPtr* oop_type, PhaseTransform *phase, bool allow_new_nodes) {1369Node *length = in(AllocateNode::ALength);1370assert(length != NULL, "length is not null");13711372const TypeInt* length_type = phase->find_int_type(length);1373const TypeAryPtr* ary_type = oop_type->isa_aryptr();13741375if (ary_type != NULL && length_type != NULL) {1376const TypeInt* narrow_length_type = ary_type->narrow_size_type(length_type);1377if (narrow_length_type != length_type) {1378// Assert one of:1379// - the narrow_length is 01380// - the narrow_length is not wider than length1381assert(narrow_length_type == TypeInt::ZERO ||1382length_type->is_con() && narrow_length_type->is_con() &&1383(narrow_length_type->_hi <= length_type->_lo) ||1384(narrow_length_type->_hi <= length_type->_hi &&1385narrow_length_type->_lo >= length_type->_lo),1386"narrow type must be narrower than length type");13871388// Return NULL if new nodes are not allowed1389if (!allow_new_nodes) return NULL;1390// Create a cast which is control dependent on the initialization to1391// propagate the fact that the array length must be positive.1392length = new (phase->C) CastIINode(length, narrow_length_type);1393length->set_req(0, initialization()->proj_out(0));1394}1395}13961397return length;1398}13991400//=============================================================================1401uint LockNode::size_of() const { return sizeof(*this); }14021403// Redundant lock elimination1404//1405// There are various patterns of locking where we release and1406// immediately reacquire a lock in a piece of code where no operations1407// occur in between that would be observable. In those cases we can1408// skip releasing and reacquiring the lock without violating any1409// fairness requirements. Doing this around a loop could cause a lock1410// to be held for a very long time so we concentrate on non-looping1411// control flow. We also require that the operations are fully1412// redundant meaning that we don't introduce new lock operations on1413// some paths so to be able to eliminate it on others ala PRE. This1414// would probably require some more extensive graph manipulation to1415// guarantee that the memory edges were all handled correctly.1416//1417// Assuming p is a simple predicate which can't trap in any way and s1418// is a synchronized method consider this code:1419//1420// s();1421// if (p)1422// s();1423// else1424// s();1425// s();1426//1427// 1. The unlocks of the first call to s can be eliminated if the1428// locks inside the then and else branches are eliminated.1429//1430// 2. The unlocks of the then and else branches can be eliminated if1431// the lock of the final call to s is eliminated.1432//1433// Either of these cases subsumes the simple case of sequential control flow1434//1435// Addtionally we can eliminate versions without the else case:1436//1437// s();1438// if (p)1439// s();1440// s();1441//1442// 3. In this case we eliminate the unlock of the first s, the lock1443// and unlock in the then case and the lock in the final s.1444//1445// Note also that in all these cases the then/else pieces don't have1446// to be trivial as long as they begin and end with synchronization1447// operations.1448//1449// s();1450// if (p)1451// s();1452// f();1453// s();1454// s();1455//1456// The code will work properly for this case, leaving in the unlock1457// before the call to f and the relock after it.1458//1459// A potentially interesting case which isn't handled here is when the1460// locking is partially redundant.1461//1462// s();1463// if (p)1464// s();1465//1466// This could be eliminated putting unlocking on the else case and1467// eliminating the first unlock and the lock in the then side.1468// Alternatively the unlock could be moved out of the then side so it1469// was after the merge and the first unlock and second lock1470// eliminated. This might require less manipulation of the memory1471// state to get correct.1472//1473// Additionally we might allow work between a unlock and lock before1474// giving up eliminating the locks. The current code disallows any1475// conditional control flow between these operations. A formulation1476// similar to partial redundancy elimination computing the1477// availability of unlocking and the anticipatability of locking at a1478// program point would allow detection of fully redundant locking with1479// some amount of work in between. I'm not sure how often I really1480// think that would occur though. Most of the cases I've seen1481// indicate it's likely non-trivial work would occur in between.1482// There may be other more complicated constructs where we could1483// eliminate locking but I haven't seen any others appear as hot or1484// interesting.1485//1486// Locking and unlocking have a canonical form in ideal that looks1487// roughly like this:1488//1489// <obj>1490// | \\------+1491// | \ \1492// | BoxLock \1493// | | | \1494// | | \ \1495// | | FastLock1496// | | /1497// | | /1498// | | |1499//1500// Lock1501// |1502// Proj #01503// |1504// MembarAcquire1505// |1506// Proj #01507//1508// MembarRelease1509// |1510// Proj #01511// |1512// Unlock1513// |1514// Proj #01515//1516//1517// This code proceeds by processing Lock nodes during PhaseIterGVN1518// and searching back through its control for the proper code1519// patterns. Once it finds a set of lock and unlock operations to1520// eliminate they are marked as eliminatable which causes the1521// expansion of the Lock and Unlock macro nodes to make the operation a NOP1522//1523//=============================================================================15241525//1526// Utility function to skip over uninteresting control nodes. Nodes skipped are:1527// - copy regions. (These may not have been optimized away yet.)1528// - eliminated locking nodes1529//1530static Node *next_control(Node *ctrl) {1531if (ctrl == NULL)1532return NULL;1533while (1) {1534if (ctrl->is_Region()) {1535RegionNode *r = ctrl->as_Region();1536Node *n = r->is_copy();1537if (n == NULL)1538break; // hit a region, return it1539else1540ctrl = n;1541} else if (ctrl->is_Proj()) {1542Node *in0 = ctrl->in(0);1543if (in0->is_AbstractLock() && in0->as_AbstractLock()->is_eliminated()) {1544ctrl = in0->in(0);1545} else {1546break;1547}1548} else {1549break; // found an interesting control1550}1551}1552return ctrl;1553}1554//1555// Given a control, see if it's the control projection of an Unlock which1556// operating on the same object as lock.1557//1558bool AbstractLockNode::find_matching_unlock(const Node* ctrl, LockNode* lock,1559GrowableArray<AbstractLockNode*> &lock_ops) {1560ProjNode *ctrl_proj = (ctrl->is_Proj()) ? ctrl->as_Proj() : NULL;1561if (ctrl_proj != NULL && ctrl_proj->_con == TypeFunc::Control) {1562Node *n = ctrl_proj->in(0);1563if (n != NULL && n->is_Unlock()) {1564UnlockNode *unlock = n->as_Unlock();1565Node* lock_obj = lock->obj_node();1566Node* unlock_obj = unlock->obj_node();1567#if INCLUDE_ALL_GCS1568if (UseShenandoahGC) {1569lock_obj = ShenandoahBarrierSetC2::bsc2()->step_over_gc_barrier(lock_obj);1570unlock_obj = ShenandoahBarrierSetC2::bsc2()->step_over_gc_barrier(unlock_obj);1571}1572#endif1573if (lock_obj->eqv_uncast(unlock_obj) &&1574BoxLockNode::same_slot(lock->box_node(), unlock->box_node()) &&1575!unlock->is_eliminated()) {1576lock_ops.append(unlock);1577return true;1578}1579}1580}1581return false;1582}15831584//1585// Find the lock matching an unlock. Returns null if a safepoint1586// or complicated control is encountered first.1587LockNode *AbstractLockNode::find_matching_lock(UnlockNode* unlock) {1588LockNode *lock_result = NULL;1589// find the matching lock, or an intervening safepoint1590Node *ctrl = next_control(unlock->in(0));1591while (1) {1592assert(ctrl != NULL, "invalid control graph");1593assert(!ctrl->is_Start(), "missing lock for unlock");1594if (ctrl->is_top()) break; // dead control path1595if (ctrl->is_Proj()) ctrl = ctrl->in(0);1596if (ctrl->is_SafePoint()) {1597break; // found a safepoint (may be the lock we are searching for)1598} else if (ctrl->is_Region()) {1599// Check for a simple diamond pattern. Punt on anything more complicated1600if (ctrl->req() == 3 && ctrl->in(1) != NULL && ctrl->in(2) != NULL) {1601Node *in1 = next_control(ctrl->in(1));1602Node *in2 = next_control(ctrl->in(2));1603if (((in1->is_IfTrue() && in2->is_IfFalse()) ||1604(in2->is_IfTrue() && in1->is_IfFalse())) && (in1->in(0) == in2->in(0))) {1605ctrl = next_control(in1->in(0)->in(0));1606} else {1607break;1608}1609} else {1610break;1611}1612} else {1613ctrl = next_control(ctrl->in(0)); // keep searching1614}1615}1616if (ctrl->is_Lock()) {1617LockNode *lock = ctrl->as_Lock();1618Node* lock_obj = lock->obj_node();1619Node* unlock_obj = unlock->obj_node();1620#if INCLUDE_ALL_GCS1621if (UseShenandoahGC) {1622lock_obj = ShenandoahBarrierSetC2::bsc2()->step_over_gc_barrier(lock_obj);1623unlock_obj = ShenandoahBarrierSetC2::bsc2()->step_over_gc_barrier(unlock_obj);1624}1625#endif1626if (lock_obj->eqv_uncast(unlock_obj) &&1627BoxLockNode::same_slot(lock->box_node(), unlock->box_node())) {1628lock_result = lock;1629}1630}1631return lock_result;1632}16331634// This code corresponds to case 3 above.16351636bool AbstractLockNode::find_lock_and_unlock_through_if(Node* node, LockNode* lock,1637GrowableArray<AbstractLockNode*> &lock_ops) {1638Node* if_node = node->in(0);1639bool if_true = node->is_IfTrue();16401641if (if_node->is_If() && if_node->outcnt() == 2 && (if_true || node->is_IfFalse())) {1642Node *lock_ctrl = next_control(if_node->in(0));1643if (find_matching_unlock(lock_ctrl, lock, lock_ops)) {1644Node* lock1_node = NULL;1645ProjNode* proj = if_node->as_If()->proj_out(!if_true);1646if (if_true) {1647if (proj->is_IfFalse() && proj->outcnt() == 1) {1648lock1_node = proj->unique_out();1649}1650} else {1651if (proj->is_IfTrue() && proj->outcnt() == 1) {1652lock1_node = proj->unique_out();1653}1654}1655if (lock1_node != NULL && lock1_node->is_Lock()) {1656LockNode *lock1 = lock1_node->as_Lock();1657Node* lock_obj = lock->obj_node();1658Node* lock1_obj = lock1->obj_node();1659#if INCLUDE_ALL_GCS1660if (UseShenandoahGC) {1661lock_obj = ShenandoahBarrierSetC2::bsc2()->step_over_gc_barrier(lock_obj);1662lock1_obj = ShenandoahBarrierSetC2::bsc2()->step_over_gc_barrier(lock1_obj);1663}1664#endif1665if (lock_obj->eqv_uncast(lock1_obj) &&1666BoxLockNode::same_slot(lock->box_node(), lock1->box_node()) &&1667!lock1->is_eliminated()) {1668lock_ops.append(lock1);1669return true;1670}1671}1672}1673}16741675lock_ops.trunc_to(0);1676return false;1677}16781679bool AbstractLockNode::find_unlocks_for_region(const RegionNode* region, LockNode* lock,1680GrowableArray<AbstractLockNode*> &lock_ops) {1681// check each control merging at this point for a matching unlock.1682// in(0) should be self edge so skip it.1683for (int i = 1; i < (int)region->req(); i++) {1684Node *in_node = next_control(region->in(i));1685if (in_node != NULL) {1686if (find_matching_unlock(in_node, lock, lock_ops)) {1687// found a match so keep on checking.1688continue;1689} else if (find_lock_and_unlock_through_if(in_node, lock, lock_ops)) {1690continue;1691}16921693// If we fall through to here then it was some kind of node we1694// don't understand or there wasn't a matching unlock, so give1695// up trying to merge locks.1696lock_ops.trunc_to(0);1697return false;1698}1699}1700return true;17011702}17031704#ifndef PRODUCT1705//1706// Create a counter which counts the number of times this lock is acquired1707//1708void AbstractLockNode::create_lock_counter(JVMState* state) {1709_counter = OptoRuntime::new_named_counter(state, NamedCounter::LockCounter);1710}17111712void AbstractLockNode::set_eliminated_lock_counter() {1713if (_counter) {1714// Update the counter to indicate that this lock was eliminated.1715// The counter update code will stay around even though the1716// optimizer will eliminate the lock operation itself.1717_counter->set_tag(NamedCounter::EliminatedLockCounter);1718}1719}1720#endif17211722//=============================================================================1723Node *LockNode::Ideal(PhaseGVN *phase, bool can_reshape) {17241725// perform any generic optimizations first (returns 'this' or NULL)1726Node *result = SafePointNode::Ideal(phase, can_reshape);1727if (result != NULL) return result;1728// Don't bother trying to transform a dead node1729if (in(0) && in(0)->is_top()) return NULL;17301731// Now see if we can optimize away this lock. We don't actually1732// remove the locking here, we simply set the _eliminate flag which1733// prevents macro expansion from expanding the lock. Since we don't1734// modify the graph, the value returned from this function is the1735// one computed above.1736if (can_reshape && EliminateLocks && !is_non_esc_obj()) {1737//1738// If we are locking an unescaped object, the lock/unlock is unnecessary1739//1740ConnectionGraph *cgr = phase->C->congraph();1741if (cgr != NULL && cgr->not_global_escape(obj_node())) {1742assert(!is_eliminated() || is_coarsened(), "sanity");1743// The lock could be marked eliminated by lock coarsening1744// code during first IGVN before EA. Replace coarsened flag1745// to eliminate all associated locks/unlocks.1746#ifdef ASSERT1747this->log_lock_optimization(phase->C,"eliminate_lock_set_non_esc1");1748#endif1749this->set_non_esc_obj();1750return result;1751}17521753//1754// Try lock coarsening1755//1756PhaseIterGVN* iter = phase->is_IterGVN();1757if (iter != NULL && !is_eliminated()) {17581759GrowableArray<AbstractLockNode*> lock_ops;17601761Node *ctrl = next_control(in(0));17621763// now search back for a matching Unlock1764if (find_matching_unlock(ctrl, this, lock_ops)) {1765// found an unlock directly preceding this lock. This is the1766// case of single unlock directly control dependent on a1767// single lock which is the trivial version of case 1 or 2.1768} else if (ctrl->is_Region() ) {1769if (find_unlocks_for_region(ctrl->as_Region(), this, lock_ops)) {1770// found lock preceded by multiple unlocks along all paths1771// joining at this point which is case 3 in description above.1772}1773} else {1774// see if this lock comes from either half of an if and the1775// predecessors merges unlocks and the other half of the if1776// performs a lock.1777if (find_lock_and_unlock_through_if(ctrl, this, lock_ops)) {1778// found unlock splitting to an if with locks on both branches.1779}1780}17811782if (lock_ops.length() > 0) {1783// add ourselves to the list of locks to be eliminated.1784lock_ops.append(this);17851786#ifndef PRODUCT1787if (PrintEliminateLocks) {1788int locks = 0;1789int unlocks = 0;1790for (int i = 0; i < lock_ops.length(); i++) {1791AbstractLockNode* lock = lock_ops.at(i);1792if (lock->Opcode() == Op_Lock)1793locks++;1794else1795unlocks++;1796if (Verbose) {1797lock->dump(1);1798}1799}1800tty->print_cr("***Eliminated %d unlocks and %d locks", unlocks, locks);1801}1802#endif18031804// for each of the identified locks, mark them1805// as eliminatable1806for (int i = 0; i < lock_ops.length(); i++) {1807AbstractLockNode* lock = lock_ops.at(i);18081809// Mark it eliminated by coarsening and update any counters1810#ifdef ASSERT1811lock->log_lock_optimization(phase->C, "eliminate_lock_set_coarsened");1812#endif1813lock->set_coarsened();1814}1815} else if (ctrl->is_Region() &&1816iter->_worklist.member(ctrl)) {1817// We weren't able to find any opportunities but the region this1818// lock is control dependent on hasn't been processed yet so put1819// this lock back on the worklist so we can check again once any1820// region simplification has occurred.1821iter->_worklist.push(this);1822}1823}1824}18251826return result;1827}18281829//=============================================================================1830bool LockNode::is_nested_lock_region() {1831return is_nested_lock_region(NULL);1832}18331834// p is used for access to compilation log; no logging if NULL1835bool LockNode::is_nested_lock_region(Compile * c) {1836BoxLockNode* box = box_node()->as_BoxLock();1837int stk_slot = box->stack_slot();1838if (stk_slot <= 0) {1839#ifdef ASSERT1840this->log_lock_optimization(c, "eliminate_lock_INLR_1");1841#endif1842return false; // External lock or it is not Box (Phi node).1843}18441845// Ignore complex cases: merged locks or multiple locks.1846Node* obj = obj_node();1847LockNode* unique_lock = NULL;1848if (!box->is_simple_lock_region(&unique_lock, obj)) {1849#ifdef ASSERT1850this->log_lock_optimization(c, "eliminate_lock_INLR_2a");1851#endif1852return false;1853}1854if (unique_lock != this) {1855#ifdef ASSERT1856this->log_lock_optimization(c, "eliminate_lock_INLR_2b");1857#endif1858return false;1859}18601861#if INCLUDE_ALL_GCS1862if (UseShenandoahGC) {1863obj = ShenandoahBarrierSetC2::bsc2()->step_over_gc_barrier(obj);1864}1865#endif1866// Look for external lock for the same object.1867SafePointNode* sfn = this->as_SafePoint();1868JVMState* youngest_jvms = sfn->jvms();1869int max_depth = youngest_jvms->depth();1870for (int depth = 1; depth <= max_depth; depth++) {1871JVMState* jvms = youngest_jvms->of_depth(depth);1872int num_mon = jvms->nof_monitors();1873// Loop over monitors1874for (int idx = 0; idx < num_mon; idx++) {1875Node* obj_node = sfn->monitor_obj(jvms, idx);1876#if INCLUDE_ALL_GCS1877if (UseShenandoahGC) {1878obj_node = ShenandoahBarrierSetC2::bsc2()->step_over_gc_barrier(obj_node);1879}1880#endif1881BoxLockNode* box_node = sfn->monitor_box(jvms, idx)->as_BoxLock();1882if ((box_node->stack_slot() < stk_slot) && obj_node->eqv_uncast(obj)) {1883return true;1884}1885}1886}1887#ifdef ASSERT1888this->log_lock_optimization(c, "eliminate_lock_INLR_3");1889#endif1890return false;1891}18921893//=============================================================================1894uint UnlockNode::size_of() const { return sizeof(*this); }18951896//=============================================================================1897Node *UnlockNode::Ideal(PhaseGVN *phase, bool can_reshape) {18981899// perform any generic optimizations first (returns 'this' or NULL)1900Node *result = SafePointNode::Ideal(phase, can_reshape);1901if (result != NULL) return result;1902// Don't bother trying to transform a dead node1903if (in(0) && in(0)->is_top()) return NULL;19041905// Now see if we can optimize away this unlock. We don't actually1906// remove the unlocking here, we simply set the _eliminate flag which1907// prevents macro expansion from expanding the unlock. Since we don't1908// modify the graph, the value returned from this function is the1909// one computed above.1910// Escape state is defined after Parse phase.1911if (can_reshape && EliminateLocks && !is_non_esc_obj()) {1912//1913// If we are unlocking an unescaped object, the lock/unlock is unnecessary.1914//1915ConnectionGraph *cgr = phase->C->congraph();1916if (cgr != NULL && cgr->not_global_escape(obj_node())) {1917assert(!is_eliminated() || is_coarsened(), "sanity");1918// The lock could be marked eliminated by lock coarsening1919// code during first IGVN before EA. Replace coarsened flag1920// to eliminate all associated locks/unlocks.1921#ifdef ASSERT1922this->log_lock_optimization(phase->C, "eliminate_lock_set_non_esc2");1923#endif1924this->set_non_esc_obj();1925}1926}1927return result;1928}19291930const char * AbstractLockNode::kind_as_string() const {1931return is_coarsened() ? "coarsened" :1932is_nested() ? "nested" :1933is_non_esc_obj() ? "non_escaping" :1934"?";1935}19361937void AbstractLockNode::log_lock_optimization(Compile *C, const char * tag) const {1938if (C == NULL) {1939return;1940}1941CompileLog* log = C->log();1942if (log != NULL) {1943log->begin_head("%s lock='%d' compile_id='%d' class_id='%s' kind='%s'",1944tag, is_Lock(), C->compile_id(),1945is_Unlock() ? "unlock" : is_Lock() ? "lock" : "?",1946kind_as_string());1947log->stamp();1948log->end_head();1949JVMState* p = is_Unlock() ? (as_Unlock()->dbg_jvms()) : jvms();1950while (p != NULL) {1951log->elem("jvms bci='%d' method='%d'", p->bci(), log->identify(p->method()));1952p = p->caller();1953}1954log->tail(tag);1955}1956}1957195819591960