Path: blob/master/src/hotspot/share/c1/c1_GraphBuilder.cpp
64440 views
/*1* Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "c1/c1_CFGPrinter.hpp"26#include "c1/c1_Canonicalizer.hpp"27#include "c1/c1_Compilation.hpp"28#include "c1/c1_GraphBuilder.hpp"29#include "c1/c1_InstructionPrinter.hpp"30#include "ci/ciCallSite.hpp"31#include "ci/ciField.hpp"32#include "ci/ciKlass.hpp"33#include "ci/ciMemberName.hpp"34#include "ci/ciSymbols.hpp"35#include "ci/ciUtilities.inline.hpp"36#include "compiler/compilationPolicy.hpp"37#include "compiler/compileBroker.hpp"38#include "compiler/compilerEvent.hpp"39#include "interpreter/bytecode.hpp"40#include "jfr/jfrEvents.hpp"41#include "memory/resourceArea.hpp"42#include "oops/oop.inline.hpp"43#include "runtime/sharedRuntime.hpp"44#include "runtime/vm_version.hpp"45#include "utilities/bitMap.inline.hpp"46#include "utilities/powerOfTwo.hpp"4748class BlockListBuilder {49private:50Compilation* _compilation;51IRScope* _scope;5253BlockList _blocks; // internal list of all blocks54BlockList* _bci2block; // mapping from bci to blocks for GraphBuilder5556// fields used by mark_loops57ResourceBitMap _active; // for iteration of control flow graph58ResourceBitMap _visited; // for iteration of control flow graph59intArray _loop_map; // caches the information if a block is contained in a loop60int _next_loop_index; // next free loop number61int _next_block_number; // for reverse postorder numbering of blocks6263// accessors64Compilation* compilation() const { return _compilation; }65IRScope* scope() const { return _scope; }66ciMethod* method() const { return scope()->method(); }67XHandlers* xhandlers() const { return scope()->xhandlers(); }6869// unified bailout support70void bailout(const char* msg) const { compilation()->bailout(msg); }71bool bailed_out() const { return compilation()->bailed_out(); }7273// helper functions74BlockBegin* make_block_at(int bci, BlockBegin* predecessor);75void handle_exceptions(BlockBegin* current, int cur_bci);76void handle_jsr(BlockBegin* current, int sr_bci, int next_bci);77void store_one(BlockBegin* current, int local);78void store_two(BlockBegin* current, int local);79void set_entries(int osr_bci);80void set_leaders();8182void make_loop_header(BlockBegin* block);83void mark_loops();84int mark_loops(BlockBegin* b, bool in_subroutine);8586// debugging87#ifndef PRODUCT88void print();89#endif9091public:92// creation93BlockListBuilder(Compilation* compilation, IRScope* scope, int osr_bci);9495// accessors for GraphBuilder96BlockList* bci2block() const { return _bci2block; }97};9899100// Implementation of BlockListBuilder101102BlockListBuilder::BlockListBuilder(Compilation* compilation, IRScope* scope, int osr_bci)103: _compilation(compilation)104, _scope(scope)105, _blocks(16)106, _bci2block(new BlockList(scope->method()->code_size(), NULL))107, _active() // size not known yet108, _visited() // size not known yet109, _loop_map() // size not known yet110, _next_loop_index(0)111, _next_block_number(0)112{113set_entries(osr_bci);114set_leaders();115CHECK_BAILOUT();116117mark_loops();118NOT_PRODUCT(if (PrintInitialBlockList) print());119120#ifndef PRODUCT121if (PrintCFGToFile) {122stringStream title;123title.print("BlockListBuilder ");124scope->method()->print_name(&title);125CFGPrinter::print_cfg(_bci2block, title.as_string(), false, false);126}127#endif128}129130131void BlockListBuilder::set_entries(int osr_bci) {132// generate start blocks133BlockBegin* std_entry = make_block_at(0, NULL);134if (scope()->caller() == NULL) {135std_entry->set(BlockBegin::std_entry_flag);136}137if (osr_bci != -1) {138BlockBegin* osr_entry = make_block_at(osr_bci, NULL);139osr_entry->set(BlockBegin::osr_entry_flag);140}141142// generate exception entry blocks143XHandlers* list = xhandlers();144const int n = list->length();145for (int i = 0; i < n; i++) {146XHandler* h = list->handler_at(i);147BlockBegin* entry = make_block_at(h->handler_bci(), NULL);148entry->set(BlockBegin::exception_entry_flag);149h->set_entry_block(entry);150}151}152153154BlockBegin* BlockListBuilder::make_block_at(int cur_bci, BlockBegin* predecessor) {155assert(method()->bci_block_start().at(cur_bci), "wrong block starts of MethodLivenessAnalyzer");156157BlockBegin* block = _bci2block->at(cur_bci);158if (block == NULL) {159block = new BlockBegin(cur_bci);160block->init_stores_to_locals(method()->max_locals());161_bci2block->at_put(cur_bci, block);162_blocks.append(block);163164assert(predecessor == NULL || predecessor->bci() < cur_bci, "targets for backward branches must already exist");165}166167if (predecessor != NULL) {168if (block->is_set(BlockBegin::exception_entry_flag)) {169BAILOUT_("Exception handler can be reached by both normal and exceptional control flow", block);170}171172predecessor->add_successor(block);173block->increment_total_preds();174}175176return block;177}178179180inline void BlockListBuilder::store_one(BlockBegin* current, int local) {181current->stores_to_locals().set_bit(local);182}183inline void BlockListBuilder::store_two(BlockBegin* current, int local) {184store_one(current, local);185store_one(current, local + 1);186}187188189void BlockListBuilder::handle_exceptions(BlockBegin* current, int cur_bci) {190// Draws edges from a block to its exception handlers191XHandlers* list = xhandlers();192const int n = list->length();193194for (int i = 0; i < n; i++) {195XHandler* h = list->handler_at(i);196197if (h->covers(cur_bci)) {198BlockBegin* entry = h->entry_block();199assert(entry != NULL && entry == _bci2block->at(h->handler_bci()), "entry must be set");200assert(entry->is_set(BlockBegin::exception_entry_flag), "flag must be set");201202// add each exception handler only once203if (!current->is_successor(entry)) {204current->add_successor(entry);205entry->increment_total_preds();206}207208// stop when reaching catchall209if (h->catch_type() == 0) break;210}211}212}213214void BlockListBuilder::handle_jsr(BlockBegin* current, int sr_bci, int next_bci) {215if (next_bci < method()->code_size()) {216// start a new block after jsr-bytecode and link this block into cfg217make_block_at(next_bci, current);218}219220// start a new block at the subroutine entry at mark it with special flag221BlockBegin* sr_block = make_block_at(sr_bci, current);222if (!sr_block->is_set(BlockBegin::subroutine_entry_flag)) {223sr_block->set(BlockBegin::subroutine_entry_flag);224}225}226227228void BlockListBuilder::set_leaders() {229bool has_xhandlers = xhandlers()->has_handlers();230BlockBegin* current = NULL;231232// The information which bci starts a new block simplifies the analysis233// Without it, backward branches could jump to a bci where no block was created234// during bytecode iteration. This would require the creation of a new block at the235// branch target and a modification of the successor lists.236const BitMap& bci_block_start = method()->bci_block_start();237238int end_bci = method()->code_size();239240ciBytecodeStream s(method());241while (s.next() != ciBytecodeStream::EOBC()) {242int cur_bci = s.cur_bci();243244if (bci_block_start.at(cur_bci)) {245current = make_block_at(cur_bci, current);246}247assert(current != NULL, "must have current block");248249if (has_xhandlers && GraphBuilder::can_trap(method(), s.cur_bc())) {250handle_exceptions(current, cur_bci);251}252253switch (s.cur_bc()) {254// track stores to local variables for selective creation of phi functions255case Bytecodes::_iinc: store_one(current, s.get_index()); break;256case Bytecodes::_istore: store_one(current, s.get_index()); break;257case Bytecodes::_lstore: store_two(current, s.get_index()); break;258case Bytecodes::_fstore: store_one(current, s.get_index()); break;259case Bytecodes::_dstore: store_two(current, s.get_index()); break;260case Bytecodes::_astore: store_one(current, s.get_index()); break;261case Bytecodes::_istore_0: store_one(current, 0); break;262case Bytecodes::_istore_1: store_one(current, 1); break;263case Bytecodes::_istore_2: store_one(current, 2); break;264case Bytecodes::_istore_3: store_one(current, 3); break;265case Bytecodes::_lstore_0: store_two(current, 0); break;266case Bytecodes::_lstore_1: store_two(current, 1); break;267case Bytecodes::_lstore_2: store_two(current, 2); break;268case Bytecodes::_lstore_3: store_two(current, 3); break;269case Bytecodes::_fstore_0: store_one(current, 0); break;270case Bytecodes::_fstore_1: store_one(current, 1); break;271case Bytecodes::_fstore_2: store_one(current, 2); break;272case Bytecodes::_fstore_3: store_one(current, 3); break;273case Bytecodes::_dstore_0: store_two(current, 0); break;274case Bytecodes::_dstore_1: store_two(current, 1); break;275case Bytecodes::_dstore_2: store_two(current, 2); break;276case Bytecodes::_dstore_3: store_two(current, 3); break;277case Bytecodes::_astore_0: store_one(current, 0); break;278case Bytecodes::_astore_1: store_one(current, 1); break;279case Bytecodes::_astore_2: store_one(current, 2); break;280case Bytecodes::_astore_3: store_one(current, 3); break;281282// track bytecodes that affect the control flow283case Bytecodes::_athrow: // fall through284case Bytecodes::_ret: // fall through285case Bytecodes::_ireturn: // fall through286case Bytecodes::_lreturn: // fall through287case Bytecodes::_freturn: // fall through288case Bytecodes::_dreturn: // fall through289case Bytecodes::_areturn: // fall through290case Bytecodes::_return:291current = NULL;292break;293294case Bytecodes::_ifeq: // fall through295case Bytecodes::_ifne: // fall through296case Bytecodes::_iflt: // fall through297case Bytecodes::_ifge: // fall through298case Bytecodes::_ifgt: // fall through299case Bytecodes::_ifle: // fall through300case Bytecodes::_if_icmpeq: // fall through301case Bytecodes::_if_icmpne: // fall through302case Bytecodes::_if_icmplt: // fall through303case Bytecodes::_if_icmpge: // fall through304case Bytecodes::_if_icmpgt: // fall through305case Bytecodes::_if_icmple: // fall through306case Bytecodes::_if_acmpeq: // fall through307case Bytecodes::_if_acmpne: // fall through308case Bytecodes::_ifnull: // fall through309case Bytecodes::_ifnonnull:310if (s.next_bci() < end_bci) {311make_block_at(s.next_bci(), current);312}313make_block_at(s.get_dest(), current);314current = NULL;315break;316317case Bytecodes::_goto:318make_block_at(s.get_dest(), current);319current = NULL;320break;321322case Bytecodes::_goto_w:323make_block_at(s.get_far_dest(), current);324current = NULL;325break;326327case Bytecodes::_jsr:328handle_jsr(current, s.get_dest(), s.next_bci());329current = NULL;330break;331332case Bytecodes::_jsr_w:333handle_jsr(current, s.get_far_dest(), s.next_bci());334current = NULL;335break;336337case Bytecodes::_tableswitch: {338// set block for each case339Bytecode_tableswitch sw(&s);340int l = sw.length();341for (int i = 0; i < l; i++) {342make_block_at(cur_bci + sw.dest_offset_at(i), current);343}344make_block_at(cur_bci + sw.default_offset(), current);345current = NULL;346break;347}348349case Bytecodes::_lookupswitch: {350// set block for each case351Bytecode_lookupswitch sw(&s);352int l = sw.number_of_pairs();353for (int i = 0; i < l; i++) {354make_block_at(cur_bci + sw.pair_at(i).offset(), current);355}356make_block_at(cur_bci + sw.default_offset(), current);357current = NULL;358break;359}360361default:362break;363}364}365}366367368void BlockListBuilder::mark_loops() {369ResourceMark rm;370371_active.initialize(BlockBegin::number_of_blocks());372_visited.initialize(BlockBegin::number_of_blocks());373_loop_map = intArray(BlockBegin::number_of_blocks(), BlockBegin::number_of_blocks(), 0);374_next_loop_index = 0;375_next_block_number = _blocks.length();376377// recursively iterate the control flow graph378mark_loops(_bci2block->at(0), false);379assert(_next_block_number >= 0, "invalid block numbers");380381// Remove dangling Resource pointers before the ResourceMark goes out-of-scope.382_active.resize(0);383_visited.resize(0);384}385386void BlockListBuilder::make_loop_header(BlockBegin* block) {387if (block->is_set(BlockBegin::exception_entry_flag)) {388// exception edges may look like loops but don't mark them as such389// since it screws up block ordering.390return;391}392if (!block->is_set(BlockBegin::parser_loop_header_flag)) {393block->set(BlockBegin::parser_loop_header_flag);394395assert(_loop_map.at(block->block_id()) == 0, "must not be set yet");396assert(0 <= _next_loop_index && _next_loop_index < BitsPerInt, "_next_loop_index is used as a bit-index in integer");397_loop_map.at_put(block->block_id(), 1 << _next_loop_index);398if (_next_loop_index < 31) _next_loop_index++;399} else {400// block already marked as loop header401assert(is_power_of_2((unsigned int)_loop_map.at(block->block_id())), "exactly one bit must be set");402}403}404405int BlockListBuilder::mark_loops(BlockBegin* block, bool in_subroutine) {406int block_id = block->block_id();407408if (_visited.at(block_id)) {409if (_active.at(block_id)) {410// reached block via backward branch411make_loop_header(block);412}413// return cached loop information for this block414return _loop_map.at(block_id);415}416417if (block->is_set(BlockBegin::subroutine_entry_flag)) {418in_subroutine = true;419}420421// set active and visited bits before successors are processed422_visited.set_bit(block_id);423_active.set_bit(block_id);424425intptr_t loop_state = 0;426for (int i = block->number_of_sux() - 1; i >= 0; i--) {427// recursively process all successors428loop_state |= mark_loops(block->sux_at(i), in_subroutine);429}430431// clear active-bit after all successors are processed432_active.clear_bit(block_id);433434// reverse-post-order numbering of all blocks435block->set_depth_first_number(_next_block_number);436_next_block_number--;437438if (loop_state != 0 || in_subroutine ) {439// block is contained at least in one loop, so phi functions are necessary440// phi functions are also necessary for all locals stored in a subroutine441scope()->requires_phi_function().set_union(block->stores_to_locals());442}443444if (block->is_set(BlockBegin::parser_loop_header_flag)) {445int header_loop_state = _loop_map.at(block_id);446assert(is_power_of_2((unsigned)header_loop_state), "exactly one bit must be set");447448// If the highest bit is set (i.e. when integer value is negative), the method449// has 32 or more loops. This bit is never cleared because it is used for multiple loops450if (header_loop_state >= 0) {451clear_bits(loop_state, header_loop_state);452}453}454455// cache and return loop information for this block456_loop_map.at_put(block_id, loop_state);457return loop_state;458}459460461#ifndef PRODUCT462463int compare_depth_first(BlockBegin** a, BlockBegin** b) {464return (*a)->depth_first_number() - (*b)->depth_first_number();465}466467void BlockListBuilder::print() {468tty->print("----- initial block list of BlockListBuilder for method ");469method()->print_short_name();470tty->cr();471472// better readability if blocks are sorted in processing order473_blocks.sort(compare_depth_first);474475for (int i = 0; i < _blocks.length(); i++) {476BlockBegin* cur = _blocks.at(i);477tty->print("%4d: B%-4d bci: %-4d preds: %-4d ", cur->depth_first_number(), cur->block_id(), cur->bci(), cur->total_preds());478479tty->print(cur->is_set(BlockBegin::std_entry_flag) ? " std" : " ");480tty->print(cur->is_set(BlockBegin::osr_entry_flag) ? " osr" : " ");481tty->print(cur->is_set(BlockBegin::exception_entry_flag) ? " ex" : " ");482tty->print(cur->is_set(BlockBegin::subroutine_entry_flag) ? " sr" : " ");483tty->print(cur->is_set(BlockBegin::parser_loop_header_flag) ? " lh" : " ");484485if (cur->number_of_sux() > 0) {486tty->print(" sux: ");487for (int j = 0; j < cur->number_of_sux(); j++) {488BlockBegin* sux = cur->sux_at(j);489tty->print("B%d ", sux->block_id());490}491}492tty->cr();493}494}495496#endif497498499// A simple growable array of Values indexed by ciFields500class FieldBuffer: public CompilationResourceObj {501private:502GrowableArray<Value> _values;503504public:505FieldBuffer() {}506507void kill() {508_values.trunc_to(0);509}510511Value at(ciField* field) {512assert(field->holder()->is_loaded(), "must be a loaded field");513int offset = field->offset();514if (offset < _values.length()) {515return _values.at(offset);516} else {517return NULL;518}519}520521void at_put(ciField* field, Value value) {522assert(field->holder()->is_loaded(), "must be a loaded field");523int offset = field->offset();524_values.at_put_grow(offset, value, NULL);525}526527};528529530// MemoryBuffer is fairly simple model of the current state of memory.531// It partitions memory into several pieces. The first piece is532// generic memory where little is known about the owner of the memory.533// This is conceptually represented by the tuple <O, F, V> which says534// that the field F of object O has value V. This is flattened so535// that F is represented by the offset of the field and the parallel536// arrays _objects and _values are used for O and V. Loads of O.F can537// simply use V. Newly allocated objects are kept in a separate list538// along with a parallel array for each object which represents the539// current value of its fields. Stores of the default value to fields540// which have never been stored to before are eliminated since they541// are redundant. Once newly allocated objects are stored into542// another object or they are passed out of the current compile they543// are treated like generic memory.544545class MemoryBuffer: public CompilationResourceObj {546private:547FieldBuffer _values;548GrowableArray<Value> _objects;549GrowableArray<Value> _newobjects;550GrowableArray<FieldBuffer*> _fields;551552public:553MemoryBuffer() {}554555StoreField* store(StoreField* st) {556if (!EliminateFieldAccess) {557return st;558}559560Value object = st->obj();561Value value = st->value();562ciField* field = st->field();563if (field->holder()->is_loaded()) {564int offset = field->offset();565int index = _newobjects.find(object);566if (index != -1) {567// newly allocated object with no other stores performed on this field568FieldBuffer* buf = _fields.at(index);569if (buf->at(field) == NULL && is_default_value(value)) {570#ifndef PRODUCT571if (PrintIRDuringConstruction && Verbose) {572tty->print_cr("Eliminated store for object %d:", index);573st->print_line();574}575#endif576return NULL;577} else {578buf->at_put(field, value);579}580} else {581_objects.at_put_grow(offset, object, NULL);582_values.at_put(field, value);583}584585store_value(value);586} else {587// if we held onto field names we could alias based on names but588// we don't know what's being stored to so kill it all.589kill();590}591return st;592}593594595// return true if this value correspond to the default value of a field.596bool is_default_value(Value value) {597Constant* con = value->as_Constant();598if (con) {599switch (con->type()->tag()) {600case intTag: return con->type()->as_IntConstant()->value() == 0;601case longTag: return con->type()->as_LongConstant()->value() == 0;602case floatTag: return jint_cast(con->type()->as_FloatConstant()->value()) == 0;603case doubleTag: return jlong_cast(con->type()->as_DoubleConstant()->value()) == jlong_cast(0);604case objectTag: return con->type() == objectNull;605default: ShouldNotReachHere();606}607}608return false;609}610611612// return either the actual value of a load or the load itself613Value load(LoadField* load) {614if (!EliminateFieldAccess) {615return load;616}617618if (strict_fp_requires_explicit_rounding && load->type()->is_float_kind()) {619#ifdef IA32620if (UseSSE < 2) {621// can't skip load since value might get rounded as a side effect622return load;623}624#else625Unimplemented();626#endif // IA32627}628629ciField* field = load->field();630Value object = load->obj();631if (field->holder()->is_loaded() && !field->is_volatile()) {632int offset = field->offset();633Value result = NULL;634int index = _newobjects.find(object);635if (index != -1) {636result = _fields.at(index)->at(field);637} else if (_objects.at_grow(offset, NULL) == object) {638result = _values.at(field);639}640if (result != NULL) {641#ifndef PRODUCT642if (PrintIRDuringConstruction && Verbose) {643tty->print_cr("Eliminated load: ");644load->print_line();645}646#endif647assert(result->type()->tag() == load->type()->tag(), "wrong types");648return result;649}650}651return load;652}653654// Record this newly allocated object655void new_instance(NewInstance* object) {656int index = _newobjects.length();657_newobjects.append(object);658if (_fields.at_grow(index, NULL) == NULL) {659_fields.at_put(index, new FieldBuffer());660} else {661_fields.at(index)->kill();662}663}664665void store_value(Value value) {666int index = _newobjects.find(value);667if (index != -1) {668// stored a newly allocated object into another object.669// Assume we've lost track of it as separate slice of memory.670// We could do better by keeping track of whether individual671// fields could alias each other.672_newobjects.remove_at(index);673// pull out the field info and store it at the end up the list674// of field info list to be reused later.675_fields.append(_fields.at(index));676_fields.remove_at(index);677}678}679680void kill() {681_newobjects.trunc_to(0);682_objects.trunc_to(0);683_values.kill();684}685};686687688// Implementation of GraphBuilder's ScopeData689690GraphBuilder::ScopeData::ScopeData(ScopeData* parent)691: _parent(parent)692, _bci2block(NULL)693, _scope(NULL)694, _has_handler(false)695, _stream(NULL)696, _work_list(NULL)697, _caller_stack_size(-1)698, _continuation(NULL)699, _parsing_jsr(false)700, _jsr_xhandlers(NULL)701, _num_returns(0)702, _cleanup_block(NULL)703, _cleanup_return_prev(NULL)704, _cleanup_state(NULL)705, _ignore_return(false)706{707if (parent != NULL) {708_max_inline_size = (intx) ((float) NestedInliningSizeRatio * (float) parent->max_inline_size() / 100.0f);709} else {710_max_inline_size = C1MaxInlineSize;711}712if (_max_inline_size < C1MaxTrivialSize) {713_max_inline_size = C1MaxTrivialSize;714}715}716717718void GraphBuilder::kill_all() {719if (UseLocalValueNumbering) {720vmap()->kill_all();721}722_memory->kill();723}724725726BlockBegin* GraphBuilder::ScopeData::block_at(int bci) {727if (parsing_jsr()) {728// It is necessary to clone all blocks associated with a729// subroutine, including those for exception handlers in the scope730// of the method containing the jsr (because those exception731// handlers may contain ret instructions in some cases).732BlockBegin* block = bci2block()->at(bci);733if (block != NULL && block == parent()->bci2block()->at(bci)) {734BlockBegin* new_block = new BlockBegin(block->bci());735if (PrintInitialBlockList) {736tty->print_cr("CFG: cloned block %d (bci %d) as block %d for jsr",737block->block_id(), block->bci(), new_block->block_id());738}739// copy data from cloned blocked740new_block->set_depth_first_number(block->depth_first_number());741if (block->is_set(BlockBegin::parser_loop_header_flag)) new_block->set(BlockBegin::parser_loop_header_flag);742// Preserve certain flags for assertion checking743if (block->is_set(BlockBegin::subroutine_entry_flag)) new_block->set(BlockBegin::subroutine_entry_flag);744if (block->is_set(BlockBegin::exception_entry_flag)) new_block->set(BlockBegin::exception_entry_flag);745746// copy was_visited_flag to allow early detection of bailouts747// if a block that is used in a jsr has already been visited before,748// it is shared between the normal control flow and a subroutine749// BlockBegin::try_merge returns false when the flag is set, this leads750// to a compilation bailout751if (block->is_set(BlockBegin::was_visited_flag)) new_block->set(BlockBegin::was_visited_flag);752753bci2block()->at_put(bci, new_block);754block = new_block;755}756return block;757} else {758return bci2block()->at(bci);759}760}761762763XHandlers* GraphBuilder::ScopeData::xhandlers() const {764if (_jsr_xhandlers == NULL) {765assert(!parsing_jsr(), "");766return scope()->xhandlers();767}768assert(parsing_jsr(), "");769return _jsr_xhandlers;770}771772773void GraphBuilder::ScopeData::set_scope(IRScope* scope) {774_scope = scope;775bool parent_has_handler = false;776if (parent() != NULL) {777parent_has_handler = parent()->has_handler();778}779_has_handler = parent_has_handler || scope->xhandlers()->has_handlers();780}781782783void GraphBuilder::ScopeData::set_inline_cleanup_info(BlockBegin* block,784Instruction* return_prev,785ValueStack* return_state) {786_cleanup_block = block;787_cleanup_return_prev = return_prev;788_cleanup_state = return_state;789}790791792void GraphBuilder::ScopeData::add_to_work_list(BlockBegin* block) {793if (_work_list == NULL) {794_work_list = new BlockList();795}796797if (!block->is_set(BlockBegin::is_on_work_list_flag)) {798// Do not start parsing the continuation block while in a799// sub-scope800if (parsing_jsr()) {801if (block == jsr_continuation()) {802return;803}804} else {805if (block == continuation()) {806return;807}808}809block->set(BlockBegin::is_on_work_list_flag);810_work_list->push(block);811812sort_top_into_worklist(_work_list, block);813}814}815816817void GraphBuilder::sort_top_into_worklist(BlockList* worklist, BlockBegin* top) {818assert(worklist->top() == top, "");819// sort block descending into work list820const int dfn = top->depth_first_number();821assert(dfn != -1, "unknown depth first number");822int i = worklist->length()-2;823while (i >= 0) {824BlockBegin* b = worklist->at(i);825if (b->depth_first_number() < dfn) {826worklist->at_put(i+1, b);827} else {828break;829}830i --;831}832if (i >= -1) worklist->at_put(i + 1, top);833}834835836BlockBegin* GraphBuilder::ScopeData::remove_from_work_list() {837if (is_work_list_empty()) {838return NULL;839}840return _work_list->pop();841}842843844bool GraphBuilder::ScopeData::is_work_list_empty() const {845return (_work_list == NULL || _work_list->length() == 0);846}847848849void GraphBuilder::ScopeData::setup_jsr_xhandlers() {850assert(parsing_jsr(), "");851// clone all the exception handlers from the scope852XHandlers* handlers = new XHandlers(scope()->xhandlers());853const int n = handlers->length();854for (int i = 0; i < n; i++) {855// The XHandlers need to be adjusted to dispatch to the cloned856// handler block instead of the default one but the synthetic857// unlocker needs to be handled specially. The synthetic unlocker858// should be left alone since there can be only one and all code859// should dispatch to the same one.860XHandler* h = handlers->handler_at(i);861assert(h->handler_bci() != SynchronizationEntryBCI, "must be real");862h->set_entry_block(block_at(h->handler_bci()));863}864_jsr_xhandlers = handlers;865}866867868int GraphBuilder::ScopeData::num_returns() {869if (parsing_jsr()) {870return parent()->num_returns();871}872return _num_returns;873}874875876void GraphBuilder::ScopeData::incr_num_returns() {877if (parsing_jsr()) {878parent()->incr_num_returns();879} else {880++_num_returns;881}882}883884885// Implementation of GraphBuilder886887#define INLINE_BAILOUT(msg) { inline_bailout(msg); return false; }888889890void GraphBuilder::load_constant() {891ciConstant con = stream()->get_constant();892if (con.basic_type() == T_ILLEGAL) {893// FIXME: an unresolved Dynamic constant can get here,894// and that should not terminate the whole compilation.895BAILOUT("could not resolve a constant");896} else {897ValueType* t = illegalType;898ValueStack* patch_state = NULL;899switch (con.basic_type()) {900case T_BOOLEAN: t = new IntConstant (con.as_boolean()); break;901case T_BYTE : t = new IntConstant (con.as_byte ()); break;902case T_CHAR : t = new IntConstant (con.as_char ()); break;903case T_SHORT : t = new IntConstant (con.as_short ()); break;904case T_INT : t = new IntConstant (con.as_int ()); break;905case T_LONG : t = new LongConstant (con.as_long ()); break;906case T_FLOAT : t = new FloatConstant (con.as_float ()); break;907case T_DOUBLE : t = new DoubleConstant (con.as_double ()); break;908case T_ARRAY : t = new ArrayConstant (con.as_object ()->as_array ()); break;909case T_OBJECT :910{911ciObject* obj = con.as_object();912if (!obj->is_loaded()913|| (PatchALot && obj->klass() != ciEnv::current()->String_klass())) {914// A Class, MethodType, MethodHandle, or String.915// Unloaded condy nodes show up as T_ILLEGAL, above.916patch_state = copy_state_before();917t = new ObjectConstant(obj);918} else {919// Might be a Class, MethodType, MethodHandle, or Dynamic constant920// result, which might turn out to be an array.921if (obj->is_null_object())922t = objectNull;923else if (obj->is_array())924t = new ArrayConstant(obj->as_array());925else926t = new InstanceConstant(obj->as_instance());927}928break;929}930default : ShouldNotReachHere();931}932Value x;933if (patch_state != NULL) {934x = new Constant(t, patch_state);935} else {936x = new Constant(t);937}938push(t, append(x));939}940}941942943void GraphBuilder::load_local(ValueType* type, int index) {944Value x = state()->local_at(index);945assert(x != NULL && !x->type()->is_illegal(), "access of illegal local variable");946push(type, x);947}948949950void GraphBuilder::store_local(ValueType* type, int index) {951Value x = pop(type);952store_local(state(), x, index);953}954955956void GraphBuilder::store_local(ValueStack* state, Value x, int index) {957if (parsing_jsr()) {958// We need to do additional tracking of the location of the return959// address for jsrs since we don't handle arbitrary jsr/ret960// constructs. Here we are figuring out in which circumstances we961// need to bail out.962if (x->type()->is_address()) {963scope_data()->set_jsr_return_address_local(index);964965// Also check parent jsrs (if any) at this time to see whether966// they are using this local. We don't handle skipping over a967// ret.968for (ScopeData* cur_scope_data = scope_data()->parent();969cur_scope_data != NULL && cur_scope_data->parsing_jsr() && cur_scope_data->scope() == scope();970cur_scope_data = cur_scope_data->parent()) {971if (cur_scope_data->jsr_return_address_local() == index) {972BAILOUT("subroutine overwrites return address from previous subroutine");973}974}975} else if (index == scope_data()->jsr_return_address_local()) {976scope_data()->set_jsr_return_address_local(-1);977}978}979980state->store_local(index, round_fp(x));981}982983984void GraphBuilder::load_indexed(BasicType type) {985// In case of in block code motion in range check elimination986ValueStack* state_before = copy_state_indexed_access();987compilation()->set_has_access_indexed(true);988Value index = ipop();989Value array = apop();990Value length = NULL;991if (CSEArrayLength ||992(array->as_Constant() != NULL) ||993(array->as_AccessField() && array->as_AccessField()->field()->is_constant()) ||994(array->as_NewArray() && array->as_NewArray()->length() && array->as_NewArray()->length()->type()->is_constant()) ||995(array->as_NewMultiArray() && array->as_NewMultiArray()->dims()->at(0)->type()->is_constant())) {996length = append(new ArrayLength(array, state_before));997}998push(as_ValueType(type), append(new LoadIndexed(array, index, length, type, state_before)));999}100010011002void GraphBuilder::store_indexed(BasicType type) {1003// In case of in block code motion in range check elimination1004ValueStack* state_before = copy_state_indexed_access();1005compilation()->set_has_access_indexed(true);1006Value value = pop(as_ValueType(type));1007Value index = ipop();1008Value array = apop();1009Value length = NULL;1010if (CSEArrayLength ||1011(array->as_Constant() != NULL) ||1012(array->as_AccessField() && array->as_AccessField()->field()->is_constant()) ||1013(array->as_NewArray() && array->as_NewArray()->length() && array->as_NewArray()->length()->type()->is_constant()) ||1014(array->as_NewMultiArray() && array->as_NewMultiArray()->dims()->at(0)->type()->is_constant())) {1015length = append(new ArrayLength(array, state_before));1016}1017ciType* array_type = array->declared_type();1018bool check_boolean = false;1019if (array_type != NULL) {1020if (array_type->is_loaded() &&1021array_type->as_array_klass()->element_type()->basic_type() == T_BOOLEAN) {1022assert(type == T_BYTE, "boolean store uses bastore");1023Value mask = append(new Constant(new IntConstant(1)));1024value = append(new LogicOp(Bytecodes::_iand, value, mask));1025}1026} else if (type == T_BYTE) {1027check_boolean = true;1028}1029StoreIndexed* result = new StoreIndexed(array, index, length, type, value, state_before, check_boolean);1030append(result);1031_memory->store_value(value);10321033if (type == T_OBJECT && is_profiling()) {1034// Note that we'd collect profile data in this method if we wanted it.1035compilation()->set_would_profile(true);10361037if (profile_checkcasts()) {1038result->set_profiled_method(method());1039result->set_profiled_bci(bci());1040result->set_should_profile(true);1041}1042}1043}104410451046void GraphBuilder::stack_op(Bytecodes::Code code) {1047switch (code) {1048case Bytecodes::_pop:1049{ state()->raw_pop();1050}1051break;1052case Bytecodes::_pop2:1053{ state()->raw_pop();1054state()->raw_pop();1055}1056break;1057case Bytecodes::_dup:1058{ Value w = state()->raw_pop();1059state()->raw_push(w);1060state()->raw_push(w);1061}1062break;1063case Bytecodes::_dup_x1:1064{ Value w1 = state()->raw_pop();1065Value w2 = state()->raw_pop();1066state()->raw_push(w1);1067state()->raw_push(w2);1068state()->raw_push(w1);1069}1070break;1071case Bytecodes::_dup_x2:1072{ Value w1 = state()->raw_pop();1073Value w2 = state()->raw_pop();1074Value w3 = state()->raw_pop();1075state()->raw_push(w1);1076state()->raw_push(w3);1077state()->raw_push(w2);1078state()->raw_push(w1);1079}1080break;1081case Bytecodes::_dup2:1082{ Value w1 = state()->raw_pop();1083Value w2 = state()->raw_pop();1084state()->raw_push(w2);1085state()->raw_push(w1);1086state()->raw_push(w2);1087state()->raw_push(w1);1088}1089break;1090case Bytecodes::_dup2_x1:1091{ Value w1 = state()->raw_pop();1092Value w2 = state()->raw_pop();1093Value w3 = state()->raw_pop();1094state()->raw_push(w2);1095state()->raw_push(w1);1096state()->raw_push(w3);1097state()->raw_push(w2);1098state()->raw_push(w1);1099}1100break;1101case Bytecodes::_dup2_x2:1102{ Value w1 = state()->raw_pop();1103Value w2 = state()->raw_pop();1104Value w3 = state()->raw_pop();1105Value w4 = state()->raw_pop();1106state()->raw_push(w2);1107state()->raw_push(w1);1108state()->raw_push(w4);1109state()->raw_push(w3);1110state()->raw_push(w2);1111state()->raw_push(w1);1112}1113break;1114case Bytecodes::_swap:1115{ Value w1 = state()->raw_pop();1116Value w2 = state()->raw_pop();1117state()->raw_push(w1);1118state()->raw_push(w2);1119}1120break;1121default:1122ShouldNotReachHere();1123break;1124}1125}112611271128void GraphBuilder::arithmetic_op(ValueType* type, Bytecodes::Code code, ValueStack* state_before) {1129Value y = pop(type);1130Value x = pop(type);1131Value res = new ArithmeticOp(code, x, y, state_before);1132// Note: currently single-precision floating-point rounding on Intel is handled at the LIRGenerator level1133res = append(res);1134res = round_fp(res);1135push(type, res);1136}113711381139void GraphBuilder::negate_op(ValueType* type) {1140push(type, append(new NegateOp(pop(type))));1141}114211431144void GraphBuilder::shift_op(ValueType* type, Bytecodes::Code code) {1145Value s = ipop();1146Value x = pop(type);1147// try to simplify1148// Note: This code should go into the canonicalizer as soon as it can1149// can handle canonicalized forms that contain more than one node.1150if (CanonicalizeNodes && code == Bytecodes::_iushr) {1151// pattern: x >>> s1152IntConstant* s1 = s->type()->as_IntConstant();1153if (s1 != NULL) {1154// pattern: x >>> s1, with s1 constant1155ShiftOp* l = x->as_ShiftOp();1156if (l != NULL && l->op() == Bytecodes::_ishl) {1157// pattern: (a << b) >>> s11158IntConstant* s0 = l->y()->type()->as_IntConstant();1159if (s0 != NULL) {1160// pattern: (a << s0) >>> s11161const int s0c = s0->value() & 0x1F; // only the low 5 bits are significant for shifts1162const int s1c = s1->value() & 0x1F; // only the low 5 bits are significant for shifts1163if (s0c == s1c) {1164if (s0c == 0) {1165// pattern: (a << 0) >>> 0 => simplify to: a1166ipush(l->x());1167} else {1168// pattern: (a << s0c) >>> s0c => simplify to: a & m, with m constant1169assert(0 < s0c && s0c < BitsPerInt, "adjust code below to handle corner cases");1170const int m = (1 << (BitsPerInt - s0c)) - 1;1171Value s = append(new Constant(new IntConstant(m)));1172ipush(append(new LogicOp(Bytecodes::_iand, l->x(), s)));1173}1174return;1175}1176}1177}1178}1179}1180// could not simplify1181push(type, append(new ShiftOp(code, x, s)));1182}118311841185void GraphBuilder::logic_op(ValueType* type, Bytecodes::Code code) {1186Value y = pop(type);1187Value x = pop(type);1188push(type, append(new LogicOp(code, x, y)));1189}119011911192void GraphBuilder::compare_op(ValueType* type, Bytecodes::Code code) {1193ValueStack* state_before = copy_state_before();1194Value y = pop(type);1195Value x = pop(type);1196ipush(append(new CompareOp(code, x, y, state_before)));1197}119811991200void GraphBuilder::convert(Bytecodes::Code op, BasicType from, BasicType to) {1201push(as_ValueType(to), append(new Convert(op, pop(as_ValueType(from)), as_ValueType(to))));1202}120312041205void GraphBuilder::increment() {1206int index = stream()->get_index();1207int delta = stream()->is_wide() ? (signed short)Bytes::get_Java_u2(stream()->cur_bcp() + 4) : (signed char)(stream()->cur_bcp()[2]);1208load_local(intType, index);1209ipush(append(new Constant(new IntConstant(delta))));1210arithmetic_op(intType, Bytecodes::_iadd);1211store_local(intType, index);1212}121312141215void GraphBuilder::_goto(int from_bci, int to_bci) {1216Goto *x = new Goto(block_at(to_bci), to_bci <= from_bci);1217if (is_profiling()) {1218compilation()->set_would_profile(true);1219x->set_profiled_bci(bci());1220if (profile_branches()) {1221x->set_profiled_method(method());1222x->set_should_profile(true);1223}1224}1225append(x);1226}122712281229void GraphBuilder::if_node(Value x, If::Condition cond, Value y, ValueStack* state_before) {1230BlockBegin* tsux = block_at(stream()->get_dest());1231BlockBegin* fsux = block_at(stream()->next_bci());1232bool is_bb = tsux->bci() < stream()->cur_bci() || fsux->bci() < stream()->cur_bci();1233// In case of loop invariant code motion or predicate insertion1234// before the body of a loop the state is needed1235Instruction *i = append(new If(x, cond, false, y, tsux, fsux, (is_bb || compilation()->is_optimistic()) ? state_before : NULL, is_bb));12361237assert(i->as_Goto() == NULL ||1238(i->as_Goto()->sux_at(0) == tsux && i->as_Goto()->is_safepoint() == tsux->bci() < stream()->cur_bci()) ||1239(i->as_Goto()->sux_at(0) == fsux && i->as_Goto()->is_safepoint() == fsux->bci() < stream()->cur_bci()),1240"safepoint state of Goto returned by canonicalizer incorrect");12411242if (is_profiling()) {1243If* if_node = i->as_If();1244if (if_node != NULL) {1245// Note that we'd collect profile data in this method if we wanted it.1246compilation()->set_would_profile(true);1247// At level 2 we need the proper bci to count backedges1248if_node->set_profiled_bci(bci());1249if (profile_branches()) {1250// Successors can be rotated by the canonicalizer, check for this case.1251if_node->set_profiled_method(method());1252if_node->set_should_profile(true);1253if (if_node->tsux() == fsux) {1254if_node->set_swapped(true);1255}1256}1257return;1258}12591260// Check if this If was reduced to Goto.1261Goto *goto_node = i->as_Goto();1262if (goto_node != NULL) {1263compilation()->set_would_profile(true);1264goto_node->set_profiled_bci(bci());1265if (profile_branches()) {1266goto_node->set_profiled_method(method());1267goto_node->set_should_profile(true);1268// Find out which successor is used.1269if (goto_node->default_sux() == tsux) {1270goto_node->set_direction(Goto::taken);1271} else if (goto_node->default_sux() == fsux) {1272goto_node->set_direction(Goto::not_taken);1273} else {1274ShouldNotReachHere();1275}1276}1277return;1278}1279}1280}128112821283void GraphBuilder::if_zero(ValueType* type, If::Condition cond) {1284Value y = append(new Constant(intZero));1285ValueStack* state_before = copy_state_before();1286Value x = ipop();1287if_node(x, cond, y, state_before);1288}128912901291void GraphBuilder::if_null(ValueType* type, If::Condition cond) {1292Value y = append(new Constant(objectNull));1293ValueStack* state_before = copy_state_before();1294Value x = apop();1295if_node(x, cond, y, state_before);1296}129712981299void GraphBuilder::if_same(ValueType* type, If::Condition cond) {1300ValueStack* state_before = copy_state_before();1301Value y = pop(type);1302Value x = pop(type);1303if_node(x, cond, y, state_before);1304}130513061307void GraphBuilder::jsr(int dest) {1308// We only handle well-formed jsrs (those which are "block-structured").1309// If the bytecodes are strange (jumping out of a jsr block) then we1310// might end up trying to re-parse a block containing a jsr which1311// has already been activated. Watch for this case and bail out.1312for (ScopeData* cur_scope_data = scope_data();1313cur_scope_data != NULL && cur_scope_data->parsing_jsr() && cur_scope_data->scope() == scope();1314cur_scope_data = cur_scope_data->parent()) {1315if (cur_scope_data->jsr_entry_bci() == dest) {1316BAILOUT("too-complicated jsr/ret structure");1317}1318}13191320push(addressType, append(new Constant(new AddressConstant(next_bci()))));1321if (!try_inline_jsr(dest)) {1322return; // bailed out while parsing and inlining subroutine1323}1324}132513261327void GraphBuilder::ret(int local_index) {1328if (!parsing_jsr()) BAILOUT("ret encountered while not parsing subroutine");13291330if (local_index != scope_data()->jsr_return_address_local()) {1331BAILOUT("can not handle complicated jsr/ret constructs");1332}13331334// Rets simply become (NON-SAFEPOINT) gotos to the jsr continuation1335append(new Goto(scope_data()->jsr_continuation(), false));1336}133713381339void GraphBuilder::table_switch() {1340Bytecode_tableswitch sw(stream());1341const int l = sw.length();1342if (CanonicalizeNodes && l == 1 && compilation()->env()->comp_level() != CompLevel_full_profile) {1343// total of 2 successors => use If instead of switch1344// Note: This code should go into the canonicalizer as soon as it can1345// can handle canonicalized forms that contain more than one node.1346Value key = append(new Constant(new IntConstant(sw.low_key())));1347BlockBegin* tsux = block_at(bci() + sw.dest_offset_at(0));1348BlockBegin* fsux = block_at(bci() + sw.default_offset());1349bool is_bb = tsux->bci() < bci() || fsux->bci() < bci();1350// In case of loop invariant code motion or predicate insertion1351// before the body of a loop the state is needed1352ValueStack* state_before = copy_state_if_bb(is_bb);1353append(new If(ipop(), If::eql, true, key, tsux, fsux, state_before, is_bb));1354} else {1355// collect successors1356BlockList* sux = new BlockList(l + 1, NULL);1357int i;1358bool has_bb = false;1359for (i = 0; i < l; i++) {1360sux->at_put(i, block_at(bci() + sw.dest_offset_at(i)));1361if (sw.dest_offset_at(i) < 0) has_bb = true;1362}1363// add default successor1364if (sw.default_offset() < 0) has_bb = true;1365sux->at_put(i, block_at(bci() + sw.default_offset()));1366// In case of loop invariant code motion or predicate insertion1367// before the body of a loop the state is needed1368ValueStack* state_before = copy_state_if_bb(has_bb);1369Instruction* res = append(new TableSwitch(ipop(), sux, sw.low_key(), state_before, has_bb));1370#ifdef ASSERT1371if (res->as_Goto()) {1372for (i = 0; i < l; i++) {1373if (sux->at(i) == res->as_Goto()->sux_at(0)) {1374assert(res->as_Goto()->is_safepoint() == sw.dest_offset_at(i) < 0, "safepoint state of Goto returned by canonicalizer incorrect");1375}1376}1377}1378#endif1379}1380}138113821383void GraphBuilder::lookup_switch() {1384Bytecode_lookupswitch sw(stream());1385const int l = sw.number_of_pairs();1386if (CanonicalizeNodes && l == 1 && compilation()->env()->comp_level() != CompLevel_full_profile) {1387// total of 2 successors => use If instead of switch1388// Note: This code should go into the canonicalizer as soon as it can1389// can handle canonicalized forms that contain more than one node.1390// simplify to If1391LookupswitchPair pair = sw.pair_at(0);1392Value key = append(new Constant(new IntConstant(pair.match())));1393BlockBegin* tsux = block_at(bci() + pair.offset());1394BlockBegin* fsux = block_at(bci() + sw.default_offset());1395bool is_bb = tsux->bci() < bci() || fsux->bci() < bci();1396// In case of loop invariant code motion or predicate insertion1397// before the body of a loop the state is needed1398ValueStack* state_before = copy_state_if_bb(is_bb);;1399append(new If(ipop(), If::eql, true, key, tsux, fsux, state_before, is_bb));1400} else {1401// collect successors & keys1402BlockList* sux = new BlockList(l + 1, NULL);1403intArray* keys = new intArray(l, l, 0);1404int i;1405bool has_bb = false;1406for (i = 0; i < l; i++) {1407LookupswitchPair pair = sw.pair_at(i);1408if (pair.offset() < 0) has_bb = true;1409sux->at_put(i, block_at(bci() + pair.offset()));1410keys->at_put(i, pair.match());1411}1412// add default successor1413if (sw.default_offset() < 0) has_bb = true;1414sux->at_put(i, block_at(bci() + sw.default_offset()));1415// In case of loop invariant code motion or predicate insertion1416// before the body of a loop the state is needed1417ValueStack* state_before = copy_state_if_bb(has_bb);1418Instruction* res = append(new LookupSwitch(ipop(), sux, keys, state_before, has_bb));1419#ifdef ASSERT1420if (res->as_Goto()) {1421for (i = 0; i < l; i++) {1422if (sux->at(i) == res->as_Goto()->sux_at(0)) {1423assert(res->as_Goto()->is_safepoint() == sw.pair_at(i).offset() < 0, "safepoint state of Goto returned by canonicalizer incorrect");1424}1425}1426}1427#endif1428}1429}14301431void GraphBuilder::call_register_finalizer() {1432// If the receiver requires finalization then emit code to perform1433// the registration on return.14341435// Gather some type information about the receiver1436Value receiver = state()->local_at(0);1437assert(receiver != NULL, "must have a receiver");1438ciType* declared_type = receiver->declared_type();1439ciType* exact_type = receiver->exact_type();1440if (exact_type == NULL &&1441receiver->as_Local() &&1442receiver->as_Local()->java_index() == 0) {1443ciInstanceKlass* ik = compilation()->method()->holder();1444if (ik->is_final()) {1445exact_type = ik;1446} else if (UseCHA && !(ik->has_subklass() || ik->is_interface())) {1447// test class is leaf class1448compilation()->dependency_recorder()->assert_leaf_type(ik);1449exact_type = ik;1450} else {1451declared_type = ik;1452}1453}14541455// see if we know statically that registration isn't required1456bool needs_check = true;1457if (exact_type != NULL) {1458needs_check = exact_type->as_instance_klass()->has_finalizer();1459} else if (declared_type != NULL) {1460ciInstanceKlass* ik = declared_type->as_instance_klass();1461if (!Dependencies::has_finalizable_subclass(ik)) {1462compilation()->dependency_recorder()->assert_has_no_finalizable_subclasses(ik);1463needs_check = false;1464}1465}14661467if (needs_check) {1468// Perform the registration of finalizable objects.1469ValueStack* state_before = copy_state_for_exception();1470load_local(objectType, 0);1471append_split(new Intrinsic(voidType, vmIntrinsics::_Object_init,1472state()->pop_arguments(1),1473true, state_before, true));1474}1475}147614771478void GraphBuilder::method_return(Value x, bool ignore_return) {1479if (RegisterFinalizersAtInit &&1480method()->intrinsic_id() == vmIntrinsics::_Object_init) {1481call_register_finalizer();1482}14831484// The conditions for a memory barrier are described in Parse::do_exits().1485bool need_mem_bar = false;1486if (method()->name() == ciSymbols::object_initializer_name() &&1487(scope()->wrote_final() ||1488(AlwaysSafeConstructors && scope()->wrote_fields()) ||1489(support_IRIW_for_not_multiple_copy_atomic_cpu && scope()->wrote_volatile()))) {1490need_mem_bar = true;1491}14921493BasicType bt = method()->return_type()->basic_type();1494switch (bt) {1495case T_BYTE:1496{1497Value shift = append(new Constant(new IntConstant(24)));1498x = append(new ShiftOp(Bytecodes::_ishl, x, shift));1499x = append(new ShiftOp(Bytecodes::_ishr, x, shift));1500break;1501}1502case T_SHORT:1503{1504Value shift = append(new Constant(new IntConstant(16)));1505x = append(new ShiftOp(Bytecodes::_ishl, x, shift));1506x = append(new ShiftOp(Bytecodes::_ishr, x, shift));1507break;1508}1509case T_CHAR:1510{1511Value mask = append(new Constant(new IntConstant(0xFFFF)));1512x = append(new LogicOp(Bytecodes::_iand, x, mask));1513break;1514}1515case T_BOOLEAN:1516{1517Value mask = append(new Constant(new IntConstant(1)));1518x = append(new LogicOp(Bytecodes::_iand, x, mask));1519break;1520}1521default:1522break;1523}15241525// Check to see whether we are inlining. If so, Return1526// instructions become Gotos to the continuation point.1527if (continuation() != NULL) {15281529int invoke_bci = state()->caller_state()->bci();15301531if (x != NULL && !ignore_return) {1532ciMethod* caller = state()->scope()->caller()->method();1533Bytecodes::Code invoke_raw_bc = caller->raw_code_at_bci(invoke_bci);1534if (invoke_raw_bc == Bytecodes::_invokehandle || invoke_raw_bc == Bytecodes::_invokedynamic) {1535ciType* declared_ret_type = caller->get_declared_signature_at_bci(invoke_bci)->return_type();1536if (declared_ret_type->is_klass() && x->exact_type() == NULL &&1537x->declared_type() != declared_ret_type && declared_ret_type != compilation()->env()->Object_klass()) {1538x = append(new TypeCast(declared_ret_type->as_klass(), x, copy_state_before()));1539}1540}1541}15421543assert(!method()->is_synchronized() || InlineSynchronizedMethods, "can not inline synchronized methods yet");15441545if (compilation()->env()->dtrace_method_probes()) {1546// Report exit from inline methods1547Values* args = new Values(1);1548args->push(append(new Constant(new MethodConstant(method()))));1549append(new RuntimeCall(voidType, "dtrace_method_exit", CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit), args));1550}15511552// If the inlined method is synchronized, the monitor must be1553// released before we jump to the continuation block.1554if (method()->is_synchronized()) {1555assert(state()->locks_size() == 1, "receiver must be locked here");1556monitorexit(state()->lock_at(0), SynchronizationEntryBCI);1557}15581559if (need_mem_bar) {1560append(new MemBar(lir_membar_storestore));1561}15621563// State at end of inlined method is the state of the caller1564// without the method parameters on stack, including the1565// return value, if any, of the inlined method on operand stack.1566set_state(state()->caller_state()->copy_for_parsing());1567if (x != NULL) {1568if (!ignore_return) {1569state()->push(x->type(), x);1570}1571if (profile_return() && x->type()->is_object_kind()) {1572ciMethod* caller = state()->scope()->method();1573profile_return_type(x, method(), caller, invoke_bci);1574}1575}1576Goto* goto_callee = new Goto(continuation(), false);15771578// See whether this is the first return; if so, store off some1579// of the state for later examination1580if (num_returns() == 0) {1581set_inline_cleanup_info();1582}15831584// The current bci() is in the wrong scope, so use the bci() of1585// the continuation point.1586append_with_bci(goto_callee, scope_data()->continuation()->bci());1587incr_num_returns();1588return;1589}15901591state()->truncate_stack(0);1592if (method()->is_synchronized()) {1593// perform the unlocking before exiting the method1594Value receiver;1595if (!method()->is_static()) {1596receiver = _initial_state->local_at(0);1597} else {1598receiver = append(new Constant(new ClassConstant(method()->holder())));1599}1600append_split(new MonitorExit(receiver, state()->unlock()));1601}16021603if (need_mem_bar) {1604append(new MemBar(lir_membar_storestore));1605}16061607assert(!ignore_return, "Ignoring return value works only for inlining");1608append(new Return(x));1609}16101611Value GraphBuilder::make_constant(ciConstant field_value, ciField* field) {1612if (!field_value.is_valid()) return NULL;16131614BasicType field_type = field_value.basic_type();1615ValueType* value = as_ValueType(field_value);16161617// Attach dimension info to stable arrays.1618if (FoldStableValues &&1619field->is_stable() && field_type == T_ARRAY && !field_value.is_null_or_zero()) {1620ciArray* array = field_value.as_object()->as_array();1621jint dimension = field->type()->as_array_klass()->dimension();1622value = new StableArrayConstant(array, dimension);1623}16241625switch (field_type) {1626case T_ARRAY:1627case T_OBJECT:1628if (field_value.as_object()->should_be_constant()) {1629return new Constant(value);1630}1631return NULL; // Not a constant.1632default:1633return new Constant(value);1634}1635}16361637void GraphBuilder::access_field(Bytecodes::Code code) {1638bool will_link;1639ciField* field = stream()->get_field(will_link);1640ciInstanceKlass* holder = field->holder();1641BasicType field_type = field->type()->basic_type();1642ValueType* type = as_ValueType(field_type);1643// call will_link again to determine if the field is valid.1644const bool needs_patching = !holder->is_loaded() ||1645!field->will_link(method(), code) ||1646PatchALot;16471648ValueStack* state_before = NULL;1649if (!holder->is_initialized() || needs_patching) {1650// save state before instruction for debug info when1651// deoptimization happens during patching1652state_before = copy_state_before();1653}16541655Value obj = NULL;1656if (code == Bytecodes::_getstatic || code == Bytecodes::_putstatic) {1657if (state_before != NULL) {1658// build a patching constant1659obj = new Constant(new InstanceConstant(holder->java_mirror()), state_before);1660} else {1661obj = new Constant(new InstanceConstant(holder->java_mirror()));1662}1663}16641665if (field->is_final() && (code == Bytecodes::_putfield)) {1666scope()->set_wrote_final();1667}16681669if (code == Bytecodes::_putfield) {1670scope()->set_wrote_fields();1671if (field->is_volatile()) {1672scope()->set_wrote_volatile();1673}1674}16751676const int offset = !needs_patching ? field->offset() : -1;1677switch (code) {1678case Bytecodes::_getstatic: {1679// check for compile-time constants, i.e., initialized static final fields1680Value constant = NULL;1681if (field->is_static_constant() && !PatchALot) {1682ciConstant field_value = field->constant_value();1683assert(!field->is_stable() || !field_value.is_null_or_zero(),1684"stable static w/ default value shouldn't be a constant");1685constant = make_constant(field_value, field);1686}1687if (constant != NULL) {1688push(type, append(constant));1689} else {1690if (state_before == NULL) {1691state_before = copy_state_for_exception();1692}1693push(type, append(new LoadField(append(obj), offset, field, true,1694state_before, needs_patching)));1695}1696break;1697}1698case Bytecodes::_putstatic: {1699Value val = pop(type);1700if (state_before == NULL) {1701state_before = copy_state_for_exception();1702}1703if (field->type()->basic_type() == T_BOOLEAN) {1704Value mask = append(new Constant(new IntConstant(1)));1705val = append(new LogicOp(Bytecodes::_iand, val, mask));1706}1707append(new StoreField(append(obj), offset, field, val, true, state_before, needs_patching));1708break;1709}1710case Bytecodes::_getfield: {1711// Check for compile-time constants, i.e., trusted final non-static fields.1712Value constant = NULL;1713obj = apop();1714ObjectType* obj_type = obj->type()->as_ObjectType();1715if (field->is_constant() && obj_type->is_constant() && !PatchALot) {1716ciObject* const_oop = obj_type->constant_value();1717if (!const_oop->is_null_object() && const_oop->is_loaded()) {1718ciConstant field_value = field->constant_value_of(const_oop);1719if (field_value.is_valid()) {1720constant = make_constant(field_value, field);1721// For CallSite objects add a dependency for invalidation of the optimization.1722if (field->is_call_site_target()) {1723ciCallSite* call_site = const_oop->as_call_site();1724if (!call_site->is_fully_initialized_constant_call_site()) {1725ciMethodHandle* target = field_value.as_object()->as_method_handle();1726dependency_recorder()->assert_call_site_target_value(call_site, target);1727}1728}1729}1730}1731}1732if (constant != NULL) {1733push(type, append(constant));1734} else {1735if (state_before == NULL) {1736state_before = copy_state_for_exception();1737}1738LoadField* load = new LoadField(obj, offset, field, false, state_before, needs_patching);1739Value replacement = !needs_patching ? _memory->load(load) : load;1740if (replacement != load) {1741assert(replacement->is_linked() || !replacement->can_be_linked(), "should already by linked");1742// Writing an (integer) value to a boolean, byte, char or short field includes an implicit narrowing1743// conversion. Emit an explicit conversion here to get the correct field value after the write.1744BasicType bt = field->type()->basic_type();1745switch (bt) {1746case T_BOOLEAN:1747case T_BYTE:1748replacement = append(new Convert(Bytecodes::_i2b, replacement, as_ValueType(bt)));1749break;1750case T_CHAR:1751replacement = append(new Convert(Bytecodes::_i2c, replacement, as_ValueType(bt)));1752break;1753case T_SHORT:1754replacement = append(new Convert(Bytecodes::_i2s, replacement, as_ValueType(bt)));1755break;1756default:1757break;1758}1759push(type, replacement);1760} else {1761push(type, append(load));1762}1763}1764break;1765}1766case Bytecodes::_putfield: {1767Value val = pop(type);1768obj = apop();1769if (state_before == NULL) {1770state_before = copy_state_for_exception();1771}1772if (field->type()->basic_type() == T_BOOLEAN) {1773Value mask = append(new Constant(new IntConstant(1)));1774val = append(new LogicOp(Bytecodes::_iand, val, mask));1775}1776StoreField* store = new StoreField(obj, offset, field, val, false, state_before, needs_patching);1777if (!needs_patching) store = _memory->store(store);1778if (store != NULL) {1779append(store);1780}1781break;1782}1783default:1784ShouldNotReachHere();1785break;1786}1787}178817891790Dependencies* GraphBuilder::dependency_recorder() const {1791assert(DeoptC1, "need debug information");1792return compilation()->dependency_recorder();1793}17941795// How many arguments do we want to profile?1796Values* GraphBuilder::args_list_for_profiling(ciMethod* target, int& start, bool may_have_receiver) {1797int n = 0;1798bool has_receiver = may_have_receiver && Bytecodes::has_receiver(method()->java_code_at_bci(bci()));1799start = has_receiver ? 1 : 0;1800if (profile_arguments()) {1801ciProfileData* data = method()->method_data()->bci_to_data(bci());1802if (data != NULL && (data->is_CallTypeData() || data->is_VirtualCallTypeData())) {1803n = data->is_CallTypeData() ? data->as_CallTypeData()->number_of_arguments() : data->as_VirtualCallTypeData()->number_of_arguments();1804}1805}1806// If we are inlining then we need to collect arguments to profile parameters for the target1807if (profile_parameters() && target != NULL) {1808if (target->method_data() != NULL && target->method_data()->parameters_type_data() != NULL) {1809// The receiver is profiled on method entry so it's included in1810// the number of parameters but here we're only interested in1811// actual arguments.1812n = MAX2(n, target->method_data()->parameters_type_data()->number_of_parameters() - start);1813}1814}1815if (n > 0) {1816return new Values(n);1817}1818return NULL;1819}18201821void GraphBuilder::check_args_for_profiling(Values* obj_args, int expected) {1822#ifdef ASSERT1823bool ignored_will_link;1824ciSignature* declared_signature = NULL;1825ciMethod* real_target = method()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);1826assert(expected == obj_args->max_length() || real_target->is_method_handle_intrinsic(), "missed on arg?");1827#endif1828}18291830// Collect arguments that we want to profile in a list1831Values* GraphBuilder::collect_args_for_profiling(Values* args, ciMethod* target, bool may_have_receiver) {1832int start = 0;1833Values* obj_args = args_list_for_profiling(target, start, may_have_receiver);1834if (obj_args == NULL) {1835return NULL;1836}1837int s = obj_args->max_length();1838// if called through method handle invoke, some arguments may have been popped1839for (int i = start, j = 0; j < s && i < args->length(); i++) {1840if (args->at(i)->type()->is_object_kind()) {1841obj_args->push(args->at(i));1842j++;1843}1844}1845check_args_for_profiling(obj_args, s);1846return obj_args;1847}184818491850void GraphBuilder::invoke(Bytecodes::Code code) {1851bool will_link;1852ciSignature* declared_signature = NULL;1853ciMethod* target = stream()->get_method(will_link, &declared_signature);1854ciKlass* holder = stream()->get_declared_method_holder();1855const Bytecodes::Code bc_raw = stream()->cur_bc_raw();1856assert(declared_signature != NULL, "cannot be null");1857assert(will_link == target->is_loaded(), "");18581859ciInstanceKlass* klass = target->holder();1860assert(!target->is_loaded() || klass->is_loaded(), "loaded target must imply loaded klass");18611862// check if CHA possible: if so, change the code to invoke_special1863ciInstanceKlass* calling_klass = method()->holder();1864ciInstanceKlass* callee_holder = ciEnv::get_instance_klass_for_declared_method_holder(holder);1865ciInstanceKlass* actual_recv = callee_holder;18661867CompileLog* log = compilation()->log();1868if (log != NULL)1869log->elem("call method='%d' instr='%s'",1870log->identify(target),1871Bytecodes::name(code));18721873// Some methods are obviously bindable without any type checks so1874// convert them directly to an invokespecial or invokestatic.1875if (target->is_loaded() && !target->is_abstract() && target->can_be_statically_bound()) {1876switch (bc_raw) {1877case Bytecodes::_invokeinterface:1878// convert to invokespecial if the target is the private interface method.1879if (target->is_private()) {1880assert(holder->is_interface(), "How did we get a non-interface method here!");1881code = Bytecodes::_invokespecial;1882}1883break;1884case Bytecodes::_invokevirtual:1885code = Bytecodes::_invokespecial;1886break;1887case Bytecodes::_invokehandle:1888code = target->is_static() ? Bytecodes::_invokestatic : Bytecodes::_invokespecial;1889break;1890default:1891break;1892}1893} else {1894if (bc_raw == Bytecodes::_invokehandle) {1895assert(!will_link, "should come here only for unlinked call");1896code = Bytecodes::_invokespecial;1897}1898}18991900if (code == Bytecodes::_invokespecial) {1901// Additional receiver subtype checks for interface calls via invokespecial or invokeinterface.1902ciKlass* receiver_constraint = nullptr;19031904if (bc_raw == Bytecodes::_invokeinterface) {1905receiver_constraint = holder;1906} else if (bc_raw == Bytecodes::_invokespecial && !target->is_object_initializer() && calling_klass->is_interface()) {1907receiver_constraint = calling_klass;1908}19091910if (receiver_constraint != nullptr) {1911int index = state()->stack_size() - (target->arg_size_no_receiver() + 1);1912Value receiver = state()->stack_at(index);1913CheckCast* c = new CheckCast(receiver_constraint, receiver, copy_state_before());1914// go to uncommon_trap when checkcast fails1915c->set_invokespecial_receiver_check();1916state()->stack_at_put(index, append_split(c));1917}1918}19191920// Push appendix argument (MethodType, CallSite, etc.), if one.1921bool patch_for_appendix = false;1922int patching_appendix_arg = 0;1923if (Bytecodes::has_optional_appendix(bc_raw) && (!will_link || PatchALot)) {1924Value arg = append(new Constant(new ObjectConstant(compilation()->env()->unloaded_ciinstance()), copy_state_before()));1925apush(arg);1926patch_for_appendix = true;1927patching_appendix_arg = (will_link && stream()->has_appendix()) ? 0 : 1;1928} else if (stream()->has_appendix()) {1929ciObject* appendix = stream()->get_appendix();1930Value arg = append(new Constant(new ObjectConstant(appendix)));1931apush(arg);1932}19331934ciMethod* cha_monomorphic_target = NULL;1935ciMethod* exact_target = NULL;1936Value better_receiver = NULL;1937if (UseCHA && DeoptC1 && target->is_loaded() &&1938!(// %%% FIXME: Are both of these relevant?1939target->is_method_handle_intrinsic() ||1940target->is_compiled_lambda_form()) &&1941!patch_for_appendix) {1942Value receiver = NULL;1943ciInstanceKlass* receiver_klass = NULL;1944bool type_is_exact = false;1945// try to find a precise receiver type1946if (will_link && !target->is_static()) {1947int index = state()->stack_size() - (target->arg_size_no_receiver() + 1);1948receiver = state()->stack_at(index);1949ciType* type = receiver->exact_type();1950if (type != NULL && type->is_loaded() &&1951type->is_instance_klass() && !type->as_instance_klass()->is_interface()) {1952receiver_klass = (ciInstanceKlass*) type;1953type_is_exact = true;1954}1955if (type == NULL) {1956type = receiver->declared_type();1957if (type != NULL && type->is_loaded() &&1958type->is_instance_klass() && !type->as_instance_klass()->is_interface()) {1959receiver_klass = (ciInstanceKlass*) type;1960if (receiver_klass->is_leaf_type() && !receiver_klass->is_final()) {1961// Insert a dependency on this type since1962// find_monomorphic_target may assume it's already done.1963dependency_recorder()->assert_leaf_type(receiver_klass);1964type_is_exact = true;1965}1966}1967}1968}1969if (receiver_klass != NULL && type_is_exact &&1970receiver_klass->is_loaded() && code != Bytecodes::_invokespecial) {1971// If we have the exact receiver type we can bind directly to1972// the method to call.1973exact_target = target->resolve_invoke(calling_klass, receiver_klass);1974if (exact_target != NULL) {1975target = exact_target;1976code = Bytecodes::_invokespecial;1977}1978}1979if (receiver_klass != NULL &&1980receiver_klass->is_subtype_of(actual_recv) &&1981actual_recv->is_initialized()) {1982actual_recv = receiver_klass;1983}19841985if ((code == Bytecodes::_invokevirtual && callee_holder->is_initialized()) ||1986(code == Bytecodes::_invokeinterface && callee_holder->is_initialized() && !actual_recv->is_interface())) {1987// Use CHA on the receiver to select a more precise method.1988cha_monomorphic_target = target->find_monomorphic_target(calling_klass, callee_holder, actual_recv);1989} else if (code == Bytecodes::_invokeinterface && callee_holder->is_loaded() && receiver != NULL) {1990assert(callee_holder->is_interface(), "invokeinterface to non interface?");1991// If there is only one implementor of this interface then we1992// may be able bind this invoke directly to the implementing1993// klass but we need both a dependence on the single interface1994// and on the method we bind to. Additionally since all we know1995// about the receiver type is the it's supposed to implement the1996// interface we have to insert a check that it's the class we1997// expect. Interface types are not checked by the verifier so1998// they are roughly equivalent to Object.1999// The number of implementors for declared_interface is less or2000// equal to the number of implementors for target->holder() so2001// if number of implementors of target->holder() == 1 then2002// number of implementors for decl_interface is 0 or 1. If2003// it's 0 then no class implements decl_interface and there's2004// no point in inlining.2005ciInstanceKlass* declared_interface = callee_holder;2006ciInstanceKlass* singleton = declared_interface->unique_implementor();2007if (singleton != NULL) {2008assert(singleton != declared_interface, "not a unique implementor");2009cha_monomorphic_target = target->find_monomorphic_target(calling_klass, declared_interface, singleton);2010if (cha_monomorphic_target != NULL) {2011if (cha_monomorphic_target->holder() != compilation()->env()->Object_klass()) {2012ciInstanceKlass* holder = cha_monomorphic_target->holder();2013ciInstanceKlass* constraint = (holder->is_subtype_of(singleton) ? holder : singleton); // avoid upcasts2014actual_recv = declared_interface;20152016// insert a check it's really the expected class.2017CheckCast* c = new CheckCast(constraint, receiver, copy_state_for_exception());2018c->set_incompatible_class_change_check();2019c->set_direct_compare(constraint->is_final());2020// pass the result of the checkcast so that the compiler has2021// more accurate type info in the inlinee2022better_receiver = append_split(c);20232024dependency_recorder()->assert_unique_implementor(declared_interface, singleton);2025} else {2026cha_monomorphic_target = NULL; // subtype check against Object is useless2027}2028}2029}2030}2031}20322033if (cha_monomorphic_target != NULL) {2034assert(!target->can_be_statically_bound() || target == cha_monomorphic_target, "");2035assert(!cha_monomorphic_target->is_abstract(), "");2036if (!cha_monomorphic_target->can_be_statically_bound(actual_recv)) {2037// If we inlined because CHA revealed only a single target method,2038// then we are dependent on that target method not getting overridden2039// by dynamic class loading. Be sure to test the "static" receiver2040// dest_method here, as opposed to the actual receiver, which may2041// falsely lead us to believe that the receiver is final or private.2042dependency_recorder()->assert_unique_concrete_method(actual_recv, cha_monomorphic_target, callee_holder, target);2043}2044code = Bytecodes::_invokespecial;2045}20462047// check if we could do inlining2048if (!PatchALot && Inline && target->is_loaded() && !patch_for_appendix &&2049callee_holder->is_loaded()) { // the effect of symbolic reference resolution20502051// callee is known => check if we have static binding2052if ((code == Bytecodes::_invokestatic && klass->is_initialized()) || // invokestatic involves an initialization barrier on declaring class2053code == Bytecodes::_invokespecial ||2054(code == Bytecodes::_invokevirtual && target->is_final_method()) ||2055code == Bytecodes::_invokedynamic) {2056// static binding => check if callee is ok2057ciMethod* inline_target = (cha_monomorphic_target != NULL) ? cha_monomorphic_target : target;2058bool holder_known = (cha_monomorphic_target != NULL) || (exact_target != NULL);2059bool success = try_inline(inline_target, holder_known, false /* ignore_return */, code, better_receiver);20602061CHECK_BAILOUT();2062clear_inline_bailout();20632064if (success) {2065// Register dependence if JVMTI has either breakpoint2066// setting or hotswapping of methods capabilities since they may2067// cause deoptimization.2068if (compilation()->env()->jvmti_can_hotswap_or_post_breakpoint()) {2069dependency_recorder()->assert_evol_method(inline_target);2070}2071return;2072}2073} else {2074print_inlining(target, "no static binding", /*success*/ false);2075}2076} else {2077print_inlining(target, "not inlineable", /*success*/ false);2078}20792080// If we attempted an inline which did not succeed because of a2081// bailout during construction of the callee graph, the entire2082// compilation has to be aborted. This is fairly rare and currently2083// seems to only occur for jasm-generated classes which contain2084// jsr/ret pairs which are not associated with finally clauses and2085// do not have exception handlers in the containing method, and are2086// therefore not caught early enough to abort the inlining without2087// corrupting the graph. (We currently bail out with a non-empty2088// stack at a ret in these situations.)2089CHECK_BAILOUT();20902091// inlining not successful => standard invoke2092ValueType* result_type = as_ValueType(declared_signature->return_type());2093ValueStack* state_before = copy_state_exhandling();20942095// The bytecode (code) might change in this method so we are checking this very late.2096const bool has_receiver =2097code == Bytecodes::_invokespecial ||2098code == Bytecodes::_invokevirtual ||2099code == Bytecodes::_invokeinterface;2100Values* args = state()->pop_arguments(target->arg_size_no_receiver() + patching_appendix_arg);2101Value recv = has_receiver ? apop() : NULL;21022103// A null check is required here (when there is a receiver) for any of the following cases2104// - invokespecial, always need a null check.2105// - invokevirtual, when the target is final and loaded. Calls to final targets will become optimized2106// and require null checking. If the target is loaded a null check is emitted here.2107// If the target isn't loaded the null check must happen after the call resolution. We achieve that2108// by using the target methods unverified entry point (see CompiledIC::compute_monomorphic_entry).2109// (The JVM specification requires that LinkageError must be thrown before a NPE. An unloaded target may2110// potentially fail, and can't have the null check before the resolution.)2111// - A call that will be profiled. (But we can't add a null check when the target is unloaded, by the same2112// reason as above, so calls with a receiver to unloaded targets can't be profiled.)2113//2114// Normal invokevirtual will perform the null check during lookup21152116bool need_null_check = (code == Bytecodes::_invokespecial) ||2117(target->is_loaded() && (target->is_final_method() || (is_profiling() && profile_calls())));21182119if (need_null_check) {2120if (recv != NULL) {2121null_check(recv);2122}21232124if (is_profiling()) {2125// Note that we'd collect profile data in this method if we wanted it.2126compilation()->set_would_profile(true);21272128if (profile_calls()) {2129assert(cha_monomorphic_target == NULL || exact_target == NULL, "both can not be set");2130ciKlass* target_klass = NULL;2131if (cha_monomorphic_target != NULL) {2132target_klass = cha_monomorphic_target->holder();2133} else if (exact_target != NULL) {2134target_klass = exact_target->holder();2135}2136profile_call(target, recv, target_klass, collect_args_for_profiling(args, NULL, false), false);2137}2138}2139}21402141Invoke* result = new Invoke(code, result_type, recv, args, target, state_before);2142// push result2143append_split(result);21442145if (result_type != voidType) {2146push(result_type, round_fp(result));2147}2148if (profile_return() && result_type->is_object_kind()) {2149profile_return_type(result, target);2150}2151}215221532154void GraphBuilder::new_instance(int klass_index) {2155ValueStack* state_before = copy_state_exhandling();2156bool will_link;2157ciKlass* klass = stream()->get_klass(will_link);2158assert(klass->is_instance_klass(), "must be an instance klass");2159NewInstance* new_instance = new NewInstance(klass->as_instance_klass(), state_before, stream()->is_unresolved_klass());2160_memory->new_instance(new_instance);2161apush(append_split(new_instance));2162}216321642165void GraphBuilder::new_type_array() {2166ValueStack* state_before = copy_state_exhandling();2167apush(append_split(new NewTypeArray(ipop(), (BasicType)stream()->get_index(), state_before)));2168}216921702171void GraphBuilder::new_object_array() {2172bool will_link;2173ciKlass* klass = stream()->get_klass(will_link);2174ValueStack* state_before = !klass->is_loaded() || PatchALot ? copy_state_before() : copy_state_exhandling();2175NewArray* n = new NewObjectArray(klass, ipop(), state_before);2176apush(append_split(n));2177}217821792180bool GraphBuilder::direct_compare(ciKlass* k) {2181if (k->is_loaded() && k->is_instance_klass() && !UseSlowPath) {2182ciInstanceKlass* ik = k->as_instance_klass();2183if (ik->is_final()) {2184return true;2185} else {2186if (DeoptC1 && UseCHA && !(ik->has_subklass() || ik->is_interface())) {2187// test class is leaf class2188dependency_recorder()->assert_leaf_type(ik);2189return true;2190}2191}2192}2193return false;2194}219521962197void GraphBuilder::check_cast(int klass_index) {2198bool will_link;2199ciKlass* klass = stream()->get_klass(will_link);2200ValueStack* state_before = !klass->is_loaded() || PatchALot ? copy_state_before() : copy_state_for_exception();2201CheckCast* c = new CheckCast(klass, apop(), state_before);2202apush(append_split(c));2203c->set_direct_compare(direct_compare(klass));22042205if (is_profiling()) {2206// Note that we'd collect profile data in this method if we wanted it.2207compilation()->set_would_profile(true);22082209if (profile_checkcasts()) {2210c->set_profiled_method(method());2211c->set_profiled_bci(bci());2212c->set_should_profile(true);2213}2214}2215}221622172218void GraphBuilder::instance_of(int klass_index) {2219bool will_link;2220ciKlass* klass = stream()->get_klass(will_link);2221ValueStack* state_before = !klass->is_loaded() || PatchALot ? copy_state_before() : copy_state_exhandling();2222InstanceOf* i = new InstanceOf(klass, apop(), state_before);2223ipush(append_split(i));2224i->set_direct_compare(direct_compare(klass));22252226if (is_profiling()) {2227// Note that we'd collect profile data in this method if we wanted it.2228compilation()->set_would_profile(true);22292230if (profile_checkcasts()) {2231i->set_profiled_method(method());2232i->set_profiled_bci(bci());2233i->set_should_profile(true);2234}2235}2236}223722382239void GraphBuilder::monitorenter(Value x, int bci) {2240// save state before locking in case of deoptimization after a NullPointerException2241ValueStack* state_before = copy_state_for_exception_with_bci(bci);2242append_with_bci(new MonitorEnter(x, state()->lock(x), state_before), bci);2243kill_all();2244}224522462247void GraphBuilder::monitorexit(Value x, int bci) {2248append_with_bci(new MonitorExit(x, state()->unlock()), bci);2249kill_all();2250}225122522253void GraphBuilder::new_multi_array(int dimensions) {2254bool will_link;2255ciKlass* klass = stream()->get_klass(will_link);2256ValueStack* state_before = !klass->is_loaded() || PatchALot ? copy_state_before() : copy_state_exhandling();22572258Values* dims = new Values(dimensions, dimensions, NULL);2259// fill in all dimensions2260int i = dimensions;2261while (i-- > 0) dims->at_put(i, ipop());2262// create array2263NewArray* n = new NewMultiArray(klass, dims, state_before);2264apush(append_split(n));2265}226622672268void GraphBuilder::throw_op(int bci) {2269// We require that the debug info for a Throw be the "state before"2270// the Throw (i.e., exception oop is still on TOS)2271ValueStack* state_before = copy_state_before_with_bci(bci);2272Throw* t = new Throw(apop(), state_before);2273// operand stack not needed after a throw2274state()->truncate_stack(0);2275append_with_bci(t, bci);2276}227722782279Value GraphBuilder::round_fp(Value fp_value) {2280if (strict_fp_requires_explicit_rounding) {2281#ifdef IA322282// no rounding needed if SSE2 is used2283if (UseSSE < 2) {2284// Must currently insert rounding node for doubleword values that2285// are results of expressions (i.e., not loads from memory or2286// constants)2287if (fp_value->type()->tag() == doubleTag &&2288fp_value->as_Constant() == NULL &&2289fp_value->as_Local() == NULL && // method parameters need no rounding2290fp_value->as_RoundFP() == NULL) {2291return append(new RoundFP(fp_value));2292}2293}2294#else2295Unimplemented();2296#endif // IA322297}2298return fp_value;2299}230023012302Instruction* GraphBuilder::append_with_bci(Instruction* instr, int bci) {2303Canonicalizer canon(compilation(), instr, bci);2304Instruction* i1 = canon.canonical();2305if (i1->is_linked() || !i1->can_be_linked()) {2306// Canonicalizer returned an instruction which was already2307// appended so simply return it.2308return i1;2309}23102311if (UseLocalValueNumbering) {2312// Lookup the instruction in the ValueMap and add it to the map if2313// it's not found.2314Instruction* i2 = vmap()->find_insert(i1);2315if (i2 != i1) {2316// found an entry in the value map, so just return it.2317assert(i2->is_linked(), "should already be linked");2318return i2;2319}2320ValueNumberingEffects vne(vmap());2321i1->visit(&vne);2322}23232324// i1 was not eliminated => append it2325assert(i1->next() == NULL, "shouldn't already be linked");2326_last = _last->set_next(i1, canon.bci());23272328if (++_instruction_count >= InstructionCountCutoff && !bailed_out()) {2329// set the bailout state but complete normal processing. We2330// might do a little more work before noticing the bailout so we2331// want processing to continue normally until it's noticed.2332bailout("Method and/or inlining is too large");2333}23342335#ifndef PRODUCT2336if (PrintIRDuringConstruction) {2337InstructionPrinter ip;2338ip.print_line(i1);2339if (Verbose) {2340state()->print();2341}2342}2343#endif23442345// save state after modification of operand stack for StateSplit instructions2346StateSplit* s = i1->as_StateSplit();2347if (s != NULL) {2348if (EliminateFieldAccess) {2349Intrinsic* intrinsic = s->as_Intrinsic();2350if (s->as_Invoke() != NULL || (intrinsic && !intrinsic->preserves_state())) {2351_memory->kill();2352}2353}2354s->set_state(state()->copy(ValueStack::StateAfter, canon.bci()));2355}23562357// set up exception handlers for this instruction if necessary2358if (i1->can_trap()) {2359i1->set_exception_handlers(handle_exception(i1));2360assert(i1->exception_state() != NULL || !i1->needs_exception_state() || bailed_out(), "handle_exception must set exception state");2361}2362return i1;2363}236423652366Instruction* GraphBuilder::append(Instruction* instr) {2367assert(instr->as_StateSplit() == NULL || instr->as_BlockEnd() != NULL, "wrong append used");2368return append_with_bci(instr, bci());2369}237023712372Instruction* GraphBuilder::append_split(StateSplit* instr) {2373return append_with_bci(instr, bci());2374}237523762377void GraphBuilder::null_check(Value value) {2378if (value->as_NewArray() != NULL || value->as_NewInstance() != NULL) {2379return;2380} else {2381Constant* con = value->as_Constant();2382if (con) {2383ObjectType* c = con->type()->as_ObjectType();2384if (c && c->is_loaded()) {2385ObjectConstant* oc = c->as_ObjectConstant();2386if (!oc || !oc->value()->is_null_object()) {2387return;2388}2389}2390}2391}2392append(new NullCheck(value, copy_state_for_exception()));2393}2394239523962397XHandlers* GraphBuilder::handle_exception(Instruction* instruction) {2398if (!has_handler() && (!instruction->needs_exception_state() || instruction->exception_state() != NULL)) {2399assert(instruction->exception_state() == NULL2400|| instruction->exception_state()->kind() == ValueStack::EmptyExceptionState2401|| (instruction->exception_state()->kind() == ValueStack::ExceptionState && _compilation->env()->should_retain_local_variables()),2402"exception_state should be of exception kind");2403return new XHandlers();2404}24052406XHandlers* exception_handlers = new XHandlers();2407ScopeData* cur_scope_data = scope_data();2408ValueStack* cur_state = instruction->state_before();2409ValueStack* prev_state = NULL;2410int scope_count = 0;24112412assert(cur_state != NULL, "state_before must be set");2413do {2414int cur_bci = cur_state->bci();2415assert(cur_scope_data->scope() == cur_state->scope(), "scopes do not match");2416assert(cur_bci == SynchronizationEntryBCI || cur_bci == cur_scope_data->stream()->cur_bci(), "invalid bci");24172418// join with all potential exception handlers2419XHandlers* list = cur_scope_data->xhandlers();2420const int n = list->length();2421for (int i = 0; i < n; i++) {2422XHandler* h = list->handler_at(i);2423if (h->covers(cur_bci)) {2424// h is a potential exception handler => join it2425compilation()->set_has_exception_handlers(true);24262427BlockBegin* entry = h->entry_block();2428if (entry == block()) {2429// It's acceptable for an exception handler to cover itself2430// but we don't handle that in the parser currently. It's2431// very rare so we bailout instead of trying to handle it.2432BAILOUT_("exception handler covers itself", exception_handlers);2433}2434assert(entry->bci() == h->handler_bci(), "must match");2435assert(entry->bci() == -1 || entry == cur_scope_data->block_at(entry->bci()), "blocks must correspond");24362437// previously this was a BAILOUT, but this is not necessary2438// now because asynchronous exceptions are not handled this way.2439assert(entry->state() == NULL || cur_state->total_locks_size() == entry->state()->total_locks_size(), "locks do not match");24402441// xhandler start with an empty expression stack2442if (cur_state->stack_size() != 0) {2443cur_state = cur_state->copy(ValueStack::ExceptionState, cur_state->bci());2444}2445if (instruction->exception_state() == NULL) {2446instruction->set_exception_state(cur_state);2447}24482449// Note: Usually this join must work. However, very2450// complicated jsr-ret structures where we don't ret from2451// the subroutine can cause the objects on the monitor2452// stacks to not match because blocks can be parsed twice.2453// The only test case we've seen so far which exhibits this2454// problem is caught by the infinite recursion test in2455// GraphBuilder::jsr() if the join doesn't work.2456if (!entry->try_merge(cur_state)) {2457BAILOUT_("error while joining with exception handler, prob. due to complicated jsr/rets", exception_handlers);2458}24592460// add current state for correct handling of phi functions at begin of xhandler2461int phi_operand = entry->add_exception_state(cur_state);24622463// add entry to the list of xhandlers of this block2464_block->add_exception_handler(entry);24652466// add back-edge from xhandler entry to this block2467if (!entry->is_predecessor(_block)) {2468entry->add_predecessor(_block);2469}24702471// clone XHandler because phi_operand and scope_count can not be shared2472XHandler* new_xhandler = new XHandler(h);2473new_xhandler->set_phi_operand(phi_operand);2474new_xhandler->set_scope_count(scope_count);2475exception_handlers->append(new_xhandler);24762477// fill in exception handler subgraph lazily2478assert(!entry->is_set(BlockBegin::was_visited_flag), "entry must not be visited yet");2479cur_scope_data->add_to_work_list(entry);24802481// stop when reaching catchall2482if (h->catch_type() == 0) {2483return exception_handlers;2484}2485}2486}24872488if (exception_handlers->length() == 0) {2489// This scope and all callees do not handle exceptions, so the local2490// variables of this scope are not needed. However, the scope itself is2491// required for a correct exception stack trace -> clear out the locals.2492if (_compilation->env()->should_retain_local_variables()) {2493cur_state = cur_state->copy(ValueStack::ExceptionState, cur_state->bci());2494} else {2495cur_state = cur_state->copy(ValueStack::EmptyExceptionState, cur_state->bci());2496}2497if (prev_state != NULL) {2498prev_state->set_caller_state(cur_state);2499}2500if (instruction->exception_state() == NULL) {2501instruction->set_exception_state(cur_state);2502}2503}25042505// Set up iteration for next time.2506// If parsing a jsr, do not grab exception handlers from the2507// parent scopes for this method (already got them, and they2508// needed to be cloned)25092510while (cur_scope_data->parsing_jsr()) {2511cur_scope_data = cur_scope_data->parent();2512}25132514assert(cur_scope_data->scope() == cur_state->scope(), "scopes do not match");2515assert(cur_state->locks_size() == 0 || cur_state->locks_size() == 1, "unlocking must be done in a catchall exception handler");25162517prev_state = cur_state;2518cur_state = cur_state->caller_state();2519cur_scope_data = cur_scope_data->parent();2520scope_count++;2521} while (cur_scope_data != NULL);25222523return exception_handlers;2524}252525262527// Helper class for simplifying Phis.2528class PhiSimplifier : public BlockClosure {2529private:2530bool _has_substitutions;2531Value simplify(Value v);25322533public:2534PhiSimplifier(BlockBegin* start) : _has_substitutions(false) {2535start->iterate_preorder(this);2536if (_has_substitutions) {2537SubstitutionResolver sr(start);2538}2539}2540void block_do(BlockBegin* b);2541bool has_substitutions() const { return _has_substitutions; }2542};254325442545Value PhiSimplifier::simplify(Value v) {2546Phi* phi = v->as_Phi();25472548if (phi == NULL) {2549// no phi function2550return v;2551} else if (v->has_subst()) {2552// already substituted; subst can be phi itself -> simplify2553return simplify(v->subst());2554} else if (phi->is_set(Phi::cannot_simplify)) {2555// already tried to simplify phi before2556return phi;2557} else if (phi->is_set(Phi::visited)) {2558// break cycles in phi functions2559return phi;2560} else if (phi->type()->is_illegal()) {2561// illegal phi functions are ignored anyway2562return phi;25632564} else {2565// mark phi function as processed to break cycles in phi functions2566phi->set(Phi::visited);25672568// simplify x = [y, x] and x = [y, y] to y2569Value subst = NULL;2570int opd_count = phi->operand_count();2571for (int i = 0; i < opd_count; i++) {2572Value opd = phi->operand_at(i);2573assert(opd != NULL, "Operand must exist!");25742575if (opd->type()->is_illegal()) {2576// if one operand is illegal, the entire phi function is illegal2577phi->make_illegal();2578phi->clear(Phi::visited);2579return phi;2580}25812582Value new_opd = simplify(opd);2583assert(new_opd != NULL, "Simplified operand must exist!");25842585if (new_opd != phi && new_opd != subst) {2586if (subst == NULL) {2587subst = new_opd;2588} else {2589// no simplification possible2590phi->set(Phi::cannot_simplify);2591phi->clear(Phi::visited);2592return phi;2593}2594}2595}25962597// sucessfully simplified phi function2598assert(subst != NULL, "illegal phi function");2599_has_substitutions = true;2600phi->clear(Phi::visited);2601phi->set_subst(subst);26022603#ifndef PRODUCT2604if (PrintPhiFunctions) {2605tty->print_cr("simplified phi function %c%d to %c%d (Block B%d)", phi->type()->tchar(), phi->id(), subst->type()->tchar(), subst->id(), phi->block()->block_id());2606}2607#endif26082609return subst;2610}2611}261226132614void PhiSimplifier::block_do(BlockBegin* b) {2615for_each_phi_fun(b, phi,2616simplify(phi);2617);26182619#ifdef ASSERT2620for_each_phi_fun(b, phi,2621assert(phi->operand_count() != 1 || phi->subst() != phi || phi->is_illegal(), "missed trivial simplification");2622);26232624ValueStack* state = b->state()->caller_state();2625for_each_state_value(state, value,2626Phi* phi = value->as_Phi();2627assert(phi == NULL || phi->block() != b, "must not have phi function to simplify in caller state");2628);2629#endif2630}26312632// This method is called after all blocks are filled with HIR instructions2633// It eliminates all Phi functions of the form x = [y, y] and x = [y, x]2634void GraphBuilder::eliminate_redundant_phis(BlockBegin* start) {2635PhiSimplifier simplifier(start);2636}263726382639void GraphBuilder::connect_to_end(BlockBegin* beg) {2640// setup iteration2641kill_all();2642_block = beg;2643_state = beg->state()->copy_for_parsing();2644_last = beg;2645iterate_bytecodes_for_block(beg->bci());2646}264726482649BlockEnd* GraphBuilder::iterate_bytecodes_for_block(int bci) {2650#ifndef PRODUCT2651if (PrintIRDuringConstruction) {2652tty->cr();2653InstructionPrinter ip;2654ip.print_instr(_block); tty->cr();2655ip.print_stack(_block->state()); tty->cr();2656ip.print_inline_level(_block);2657ip.print_head();2658tty->print_cr("locals size: %d stack size: %d", state()->locals_size(), state()->stack_size());2659}2660#endif2661_skip_block = false;2662assert(state() != NULL, "ValueStack missing!");2663CompileLog* log = compilation()->log();2664ciBytecodeStream s(method());2665s.reset_to_bci(bci);2666int prev_bci = bci;2667scope_data()->set_stream(&s);2668// iterate2669Bytecodes::Code code = Bytecodes::_illegal;2670bool push_exception = false;26712672if (block()->is_set(BlockBegin::exception_entry_flag) && block()->next() == NULL) {2673// first thing in the exception entry block should be the exception object.2674push_exception = true;2675}26762677bool ignore_return = scope_data()->ignore_return();26782679while (!bailed_out() && last()->as_BlockEnd() == NULL &&2680(code = stream()->next()) != ciBytecodeStream::EOBC() &&2681(block_at(s.cur_bci()) == NULL || block_at(s.cur_bci()) == block())) {2682assert(state()->kind() == ValueStack::Parsing, "invalid state kind");26832684if (log != NULL)2685log->set_context("bc code='%d' bci='%d'", (int)code, s.cur_bci());26862687// Check for active jsr during OSR compilation2688if (compilation()->is_osr_compile()2689&& scope()->is_top_scope()2690&& parsing_jsr()2691&& s.cur_bci() == compilation()->osr_bci()) {2692bailout("OSR not supported while a jsr is active");2693}26942695if (push_exception) {2696apush(append(new ExceptionObject()));2697push_exception = false;2698}26992700// handle bytecode2701switch (code) {2702case Bytecodes::_nop : /* nothing to do */ break;2703case Bytecodes::_aconst_null : apush(append(new Constant(objectNull ))); break;2704case Bytecodes::_iconst_m1 : ipush(append(new Constant(new IntConstant (-1)))); break;2705case Bytecodes::_iconst_0 : ipush(append(new Constant(intZero ))); break;2706case Bytecodes::_iconst_1 : ipush(append(new Constant(intOne ))); break;2707case Bytecodes::_iconst_2 : ipush(append(new Constant(new IntConstant ( 2)))); break;2708case Bytecodes::_iconst_3 : ipush(append(new Constant(new IntConstant ( 3)))); break;2709case Bytecodes::_iconst_4 : ipush(append(new Constant(new IntConstant ( 4)))); break;2710case Bytecodes::_iconst_5 : ipush(append(new Constant(new IntConstant ( 5)))); break;2711case Bytecodes::_lconst_0 : lpush(append(new Constant(new LongConstant ( 0)))); break;2712case Bytecodes::_lconst_1 : lpush(append(new Constant(new LongConstant ( 1)))); break;2713case Bytecodes::_fconst_0 : fpush(append(new Constant(new FloatConstant ( 0)))); break;2714case Bytecodes::_fconst_1 : fpush(append(new Constant(new FloatConstant ( 1)))); break;2715case Bytecodes::_fconst_2 : fpush(append(new Constant(new FloatConstant ( 2)))); break;2716case Bytecodes::_dconst_0 : dpush(append(new Constant(new DoubleConstant( 0)))); break;2717case Bytecodes::_dconst_1 : dpush(append(new Constant(new DoubleConstant( 1)))); break;2718case Bytecodes::_bipush : ipush(append(new Constant(new IntConstant(((signed char*)s.cur_bcp())[1])))); break;2719case Bytecodes::_sipush : ipush(append(new Constant(new IntConstant((short)Bytes::get_Java_u2(s.cur_bcp()+1))))); break;2720case Bytecodes::_ldc : // fall through2721case Bytecodes::_ldc_w : // fall through2722case Bytecodes::_ldc2_w : load_constant(); break;2723case Bytecodes::_iload : load_local(intType , s.get_index()); break;2724case Bytecodes::_lload : load_local(longType , s.get_index()); break;2725case Bytecodes::_fload : load_local(floatType , s.get_index()); break;2726case Bytecodes::_dload : load_local(doubleType , s.get_index()); break;2727case Bytecodes::_aload : load_local(instanceType, s.get_index()); break;2728case Bytecodes::_iload_0 : load_local(intType , 0); break;2729case Bytecodes::_iload_1 : load_local(intType , 1); break;2730case Bytecodes::_iload_2 : load_local(intType , 2); break;2731case Bytecodes::_iload_3 : load_local(intType , 3); break;2732case Bytecodes::_lload_0 : load_local(longType , 0); break;2733case Bytecodes::_lload_1 : load_local(longType , 1); break;2734case Bytecodes::_lload_2 : load_local(longType , 2); break;2735case Bytecodes::_lload_3 : load_local(longType , 3); break;2736case Bytecodes::_fload_0 : load_local(floatType , 0); break;2737case Bytecodes::_fload_1 : load_local(floatType , 1); break;2738case Bytecodes::_fload_2 : load_local(floatType , 2); break;2739case Bytecodes::_fload_3 : load_local(floatType , 3); break;2740case Bytecodes::_dload_0 : load_local(doubleType, 0); break;2741case Bytecodes::_dload_1 : load_local(doubleType, 1); break;2742case Bytecodes::_dload_2 : load_local(doubleType, 2); break;2743case Bytecodes::_dload_3 : load_local(doubleType, 3); break;2744case Bytecodes::_aload_0 : load_local(objectType, 0); break;2745case Bytecodes::_aload_1 : load_local(objectType, 1); break;2746case Bytecodes::_aload_2 : load_local(objectType, 2); break;2747case Bytecodes::_aload_3 : load_local(objectType, 3); break;2748case Bytecodes::_iaload : load_indexed(T_INT ); break;2749case Bytecodes::_laload : load_indexed(T_LONG ); break;2750case Bytecodes::_faload : load_indexed(T_FLOAT ); break;2751case Bytecodes::_daload : load_indexed(T_DOUBLE); break;2752case Bytecodes::_aaload : load_indexed(T_OBJECT); break;2753case Bytecodes::_baload : load_indexed(T_BYTE ); break;2754case Bytecodes::_caload : load_indexed(T_CHAR ); break;2755case Bytecodes::_saload : load_indexed(T_SHORT ); break;2756case Bytecodes::_istore : store_local(intType , s.get_index()); break;2757case Bytecodes::_lstore : store_local(longType , s.get_index()); break;2758case Bytecodes::_fstore : store_local(floatType , s.get_index()); break;2759case Bytecodes::_dstore : store_local(doubleType, s.get_index()); break;2760case Bytecodes::_astore : store_local(objectType, s.get_index()); break;2761case Bytecodes::_istore_0 : store_local(intType , 0); break;2762case Bytecodes::_istore_1 : store_local(intType , 1); break;2763case Bytecodes::_istore_2 : store_local(intType , 2); break;2764case Bytecodes::_istore_3 : store_local(intType , 3); break;2765case Bytecodes::_lstore_0 : store_local(longType , 0); break;2766case Bytecodes::_lstore_1 : store_local(longType , 1); break;2767case Bytecodes::_lstore_2 : store_local(longType , 2); break;2768case Bytecodes::_lstore_3 : store_local(longType , 3); break;2769case Bytecodes::_fstore_0 : store_local(floatType , 0); break;2770case Bytecodes::_fstore_1 : store_local(floatType , 1); break;2771case Bytecodes::_fstore_2 : store_local(floatType , 2); break;2772case Bytecodes::_fstore_3 : store_local(floatType , 3); break;2773case Bytecodes::_dstore_0 : store_local(doubleType, 0); break;2774case Bytecodes::_dstore_1 : store_local(doubleType, 1); break;2775case Bytecodes::_dstore_2 : store_local(doubleType, 2); break;2776case Bytecodes::_dstore_3 : store_local(doubleType, 3); break;2777case Bytecodes::_astore_0 : store_local(objectType, 0); break;2778case Bytecodes::_astore_1 : store_local(objectType, 1); break;2779case Bytecodes::_astore_2 : store_local(objectType, 2); break;2780case Bytecodes::_astore_3 : store_local(objectType, 3); break;2781case Bytecodes::_iastore : store_indexed(T_INT ); break;2782case Bytecodes::_lastore : store_indexed(T_LONG ); break;2783case Bytecodes::_fastore : store_indexed(T_FLOAT ); break;2784case Bytecodes::_dastore : store_indexed(T_DOUBLE); break;2785case Bytecodes::_aastore : store_indexed(T_OBJECT); break;2786case Bytecodes::_bastore : store_indexed(T_BYTE ); break;2787case Bytecodes::_castore : store_indexed(T_CHAR ); break;2788case Bytecodes::_sastore : store_indexed(T_SHORT ); break;2789case Bytecodes::_pop : // fall through2790case Bytecodes::_pop2 : // fall through2791case Bytecodes::_dup : // fall through2792case Bytecodes::_dup_x1 : // fall through2793case Bytecodes::_dup_x2 : // fall through2794case Bytecodes::_dup2 : // fall through2795case Bytecodes::_dup2_x1 : // fall through2796case Bytecodes::_dup2_x2 : // fall through2797case Bytecodes::_swap : stack_op(code); break;2798case Bytecodes::_iadd : arithmetic_op(intType , code); break;2799case Bytecodes::_ladd : arithmetic_op(longType , code); break;2800case Bytecodes::_fadd : arithmetic_op(floatType , code); break;2801case Bytecodes::_dadd : arithmetic_op(doubleType, code); break;2802case Bytecodes::_isub : arithmetic_op(intType , code); break;2803case Bytecodes::_lsub : arithmetic_op(longType , code); break;2804case Bytecodes::_fsub : arithmetic_op(floatType , code); break;2805case Bytecodes::_dsub : arithmetic_op(doubleType, code); break;2806case Bytecodes::_imul : arithmetic_op(intType , code); break;2807case Bytecodes::_lmul : arithmetic_op(longType , code); break;2808case Bytecodes::_fmul : arithmetic_op(floatType , code); break;2809case Bytecodes::_dmul : arithmetic_op(doubleType, code); break;2810case Bytecodes::_idiv : arithmetic_op(intType , code, copy_state_for_exception()); break;2811case Bytecodes::_ldiv : arithmetic_op(longType , code, copy_state_for_exception()); break;2812case Bytecodes::_fdiv : arithmetic_op(floatType , code); break;2813case Bytecodes::_ddiv : arithmetic_op(doubleType, code); break;2814case Bytecodes::_irem : arithmetic_op(intType , code, copy_state_for_exception()); break;2815case Bytecodes::_lrem : arithmetic_op(longType , code, copy_state_for_exception()); break;2816case Bytecodes::_frem : arithmetic_op(floatType , code); break;2817case Bytecodes::_drem : arithmetic_op(doubleType, code); break;2818case Bytecodes::_ineg : negate_op(intType ); break;2819case Bytecodes::_lneg : negate_op(longType ); break;2820case Bytecodes::_fneg : negate_op(floatType ); break;2821case Bytecodes::_dneg : negate_op(doubleType); break;2822case Bytecodes::_ishl : shift_op(intType , code); break;2823case Bytecodes::_lshl : shift_op(longType, code); break;2824case Bytecodes::_ishr : shift_op(intType , code); break;2825case Bytecodes::_lshr : shift_op(longType, code); break;2826case Bytecodes::_iushr : shift_op(intType , code); break;2827case Bytecodes::_lushr : shift_op(longType, code); break;2828case Bytecodes::_iand : logic_op(intType , code); break;2829case Bytecodes::_land : logic_op(longType, code); break;2830case Bytecodes::_ior : logic_op(intType , code); break;2831case Bytecodes::_lor : logic_op(longType, code); break;2832case Bytecodes::_ixor : logic_op(intType , code); break;2833case Bytecodes::_lxor : logic_op(longType, code); break;2834case Bytecodes::_iinc : increment(); break;2835case Bytecodes::_i2l : convert(code, T_INT , T_LONG ); break;2836case Bytecodes::_i2f : convert(code, T_INT , T_FLOAT ); break;2837case Bytecodes::_i2d : convert(code, T_INT , T_DOUBLE); break;2838case Bytecodes::_l2i : convert(code, T_LONG , T_INT ); break;2839case Bytecodes::_l2f : convert(code, T_LONG , T_FLOAT ); break;2840case Bytecodes::_l2d : convert(code, T_LONG , T_DOUBLE); break;2841case Bytecodes::_f2i : convert(code, T_FLOAT , T_INT ); break;2842case Bytecodes::_f2l : convert(code, T_FLOAT , T_LONG ); break;2843case Bytecodes::_f2d : convert(code, T_FLOAT , T_DOUBLE); break;2844case Bytecodes::_d2i : convert(code, T_DOUBLE, T_INT ); break;2845case Bytecodes::_d2l : convert(code, T_DOUBLE, T_LONG ); break;2846case Bytecodes::_d2f : convert(code, T_DOUBLE, T_FLOAT ); break;2847case Bytecodes::_i2b : convert(code, T_INT , T_BYTE ); break;2848case Bytecodes::_i2c : convert(code, T_INT , T_CHAR ); break;2849case Bytecodes::_i2s : convert(code, T_INT , T_SHORT ); break;2850case Bytecodes::_lcmp : compare_op(longType , code); break;2851case Bytecodes::_fcmpl : compare_op(floatType , code); break;2852case Bytecodes::_fcmpg : compare_op(floatType , code); break;2853case Bytecodes::_dcmpl : compare_op(doubleType, code); break;2854case Bytecodes::_dcmpg : compare_op(doubleType, code); break;2855case Bytecodes::_ifeq : if_zero(intType , If::eql); break;2856case Bytecodes::_ifne : if_zero(intType , If::neq); break;2857case Bytecodes::_iflt : if_zero(intType , If::lss); break;2858case Bytecodes::_ifge : if_zero(intType , If::geq); break;2859case Bytecodes::_ifgt : if_zero(intType , If::gtr); break;2860case Bytecodes::_ifle : if_zero(intType , If::leq); break;2861case Bytecodes::_if_icmpeq : if_same(intType , If::eql); break;2862case Bytecodes::_if_icmpne : if_same(intType , If::neq); break;2863case Bytecodes::_if_icmplt : if_same(intType , If::lss); break;2864case Bytecodes::_if_icmpge : if_same(intType , If::geq); break;2865case Bytecodes::_if_icmpgt : if_same(intType , If::gtr); break;2866case Bytecodes::_if_icmple : if_same(intType , If::leq); break;2867case Bytecodes::_if_acmpeq : if_same(objectType, If::eql); break;2868case Bytecodes::_if_acmpne : if_same(objectType, If::neq); break;2869case Bytecodes::_goto : _goto(s.cur_bci(), s.get_dest()); break;2870case Bytecodes::_jsr : jsr(s.get_dest()); break;2871case Bytecodes::_ret : ret(s.get_index()); break;2872case Bytecodes::_tableswitch : table_switch(); break;2873case Bytecodes::_lookupswitch : lookup_switch(); break;2874case Bytecodes::_ireturn : method_return(ipop(), ignore_return); break;2875case Bytecodes::_lreturn : method_return(lpop(), ignore_return); break;2876case Bytecodes::_freturn : method_return(fpop(), ignore_return); break;2877case Bytecodes::_dreturn : method_return(dpop(), ignore_return); break;2878case Bytecodes::_areturn : method_return(apop(), ignore_return); break;2879case Bytecodes::_return : method_return(NULL , ignore_return); break;2880case Bytecodes::_getstatic : // fall through2881case Bytecodes::_putstatic : // fall through2882case Bytecodes::_getfield : // fall through2883case Bytecodes::_putfield : access_field(code); break;2884case Bytecodes::_invokevirtual : // fall through2885case Bytecodes::_invokespecial : // fall through2886case Bytecodes::_invokestatic : // fall through2887case Bytecodes::_invokedynamic : // fall through2888case Bytecodes::_invokeinterface: invoke(code); break;2889case Bytecodes::_new : new_instance(s.get_index_u2()); break;2890case Bytecodes::_newarray : new_type_array(); break;2891case Bytecodes::_anewarray : new_object_array(); break;2892case Bytecodes::_arraylength : { ValueStack* state_before = copy_state_for_exception(); ipush(append(new ArrayLength(apop(), state_before))); break; }2893case Bytecodes::_athrow : throw_op(s.cur_bci()); break;2894case Bytecodes::_checkcast : check_cast(s.get_index_u2()); break;2895case Bytecodes::_instanceof : instance_of(s.get_index_u2()); break;2896case Bytecodes::_monitorenter : monitorenter(apop(), s.cur_bci()); break;2897case Bytecodes::_monitorexit : monitorexit (apop(), s.cur_bci()); break;2898case Bytecodes::_wide : ShouldNotReachHere(); break;2899case Bytecodes::_multianewarray : new_multi_array(s.cur_bcp()[3]); break;2900case Bytecodes::_ifnull : if_null(objectType, If::eql); break;2901case Bytecodes::_ifnonnull : if_null(objectType, If::neq); break;2902case Bytecodes::_goto_w : _goto(s.cur_bci(), s.get_far_dest()); break;2903case Bytecodes::_jsr_w : jsr(s.get_far_dest()); break;2904case Bytecodes::_breakpoint : BAILOUT_("concurrent setting of breakpoint", NULL);2905default : ShouldNotReachHere(); break;2906}29072908if (log != NULL)2909log->clear_context(); // skip marker if nothing was printed29102911// save current bci to setup Goto at the end2912prev_bci = s.cur_bci();29132914}2915CHECK_BAILOUT_(NULL);2916// stop processing of this block (see try_inline_full)2917if (_skip_block) {2918_skip_block = false;2919assert(_last && _last->as_BlockEnd(), "");2920return _last->as_BlockEnd();2921}2922// if there are any, check if last instruction is a BlockEnd instruction2923BlockEnd* end = last()->as_BlockEnd();2924if (end == NULL) {2925// all blocks must end with a BlockEnd instruction => add a Goto2926end = new Goto(block_at(s.cur_bci()), false);2927append(end);2928}2929assert(end == last()->as_BlockEnd(), "inconsistency");29302931assert(end->state() != NULL, "state must already be present");2932assert(end->as_Return() == NULL || end->as_Throw() == NULL || end->state()->stack_size() == 0, "stack not needed for return and throw");29332934// connect to begin & set state2935// NOTE that inlining may have changed the block we are parsing2936block()->set_end(end);2937// propagate state2938for (int i = end->number_of_sux() - 1; i >= 0; i--) {2939BlockBegin* sux = end->sux_at(i);2940assert(sux->is_predecessor(block()), "predecessor missing");2941// be careful, bailout if bytecodes are strange2942if (!sux->try_merge(end->state())) BAILOUT_("block join failed", NULL);2943scope_data()->add_to_work_list(end->sux_at(i));2944}29452946scope_data()->set_stream(NULL);29472948// done2949return end;2950}295129522953void GraphBuilder::iterate_all_blocks(bool start_in_current_block_for_inlining) {2954do {2955if (start_in_current_block_for_inlining && !bailed_out()) {2956iterate_bytecodes_for_block(0);2957start_in_current_block_for_inlining = false;2958} else {2959BlockBegin* b;2960while ((b = scope_data()->remove_from_work_list()) != NULL) {2961if (!b->is_set(BlockBegin::was_visited_flag)) {2962if (b->is_set(BlockBegin::osr_entry_flag)) {2963// we're about to parse the osr entry block, so make sure2964// we setup the OSR edge leading into this block so that2965// Phis get setup correctly.2966setup_osr_entry_block();2967// this is no longer the osr entry block, so clear it.2968b->clear(BlockBegin::osr_entry_flag);2969}2970b->set(BlockBegin::was_visited_flag);2971connect_to_end(b);2972}2973}2974}2975} while (!bailed_out() && !scope_data()->is_work_list_empty());2976}297729782979bool GraphBuilder::_can_trap [Bytecodes::number_of_java_codes];29802981void GraphBuilder::initialize() {2982// the following bytecodes are assumed to potentially2983// throw exceptions in compiled code - note that e.g.2984// monitorexit & the return bytecodes do not throw2985// exceptions since monitor pairing proved that they2986// succeed (if monitor pairing succeeded)2987Bytecodes::Code can_trap_list[] =2988{ Bytecodes::_ldc2989, Bytecodes::_ldc_w2990, Bytecodes::_ldc2_w2991, Bytecodes::_iaload2992, Bytecodes::_laload2993, Bytecodes::_faload2994, Bytecodes::_daload2995, Bytecodes::_aaload2996, Bytecodes::_baload2997, Bytecodes::_caload2998, Bytecodes::_saload2999, Bytecodes::_iastore3000, Bytecodes::_lastore3001, Bytecodes::_fastore3002, Bytecodes::_dastore3003, Bytecodes::_aastore3004, Bytecodes::_bastore3005, Bytecodes::_castore3006, Bytecodes::_sastore3007, Bytecodes::_idiv3008, Bytecodes::_ldiv3009, Bytecodes::_irem3010, Bytecodes::_lrem3011, Bytecodes::_getstatic3012, Bytecodes::_putstatic3013, Bytecodes::_getfield3014, Bytecodes::_putfield3015, Bytecodes::_invokevirtual3016, Bytecodes::_invokespecial3017, Bytecodes::_invokestatic3018, Bytecodes::_invokedynamic3019, Bytecodes::_invokeinterface3020, Bytecodes::_new3021, Bytecodes::_newarray3022, Bytecodes::_anewarray3023, Bytecodes::_arraylength3024, Bytecodes::_athrow3025, Bytecodes::_checkcast3026, Bytecodes::_instanceof3027, Bytecodes::_monitorenter3028, Bytecodes::_multianewarray3029};30303031// inititialize trap tables3032for (int i = 0; i < Bytecodes::number_of_java_codes; i++) {3033_can_trap[i] = false;3034}3035// set standard trap info3036for (uint j = 0; j < ARRAY_SIZE(can_trap_list); j++) {3037_can_trap[can_trap_list[j]] = true;3038}3039}304030413042BlockBegin* GraphBuilder::header_block(BlockBegin* entry, BlockBegin::Flag f, ValueStack* state) {3043assert(entry->is_set(f), "entry/flag mismatch");3044// create header block3045BlockBegin* h = new BlockBegin(entry->bci());3046h->set_depth_first_number(0);30473048Value l = h;3049BlockEnd* g = new Goto(entry, false);3050l->set_next(g, entry->bci());3051h->set_end(g);3052h->set(f);3053// setup header block end state3054ValueStack* s = state->copy(ValueStack::StateAfter, entry->bci()); // can use copy since stack is empty (=> no phis)3055assert(s->stack_is_empty(), "must have empty stack at entry point");3056g->set_state(s);3057return h;3058}3059306030613062BlockBegin* GraphBuilder::setup_start_block(int osr_bci, BlockBegin* std_entry, BlockBegin* osr_entry, ValueStack* state) {3063BlockBegin* start = new BlockBegin(0);30643065// This code eliminates the empty start block at the beginning of3066// each method. Previously, each method started with the3067// start-block created below, and this block was followed by the3068// header block that was always empty. This header block is only3069// necesary if std_entry is also a backward branch target because3070// then phi functions may be necessary in the header block. It's3071// also necessary when profiling so that there's a single block that3072// can increment the the counters.3073// In addition, with range check elimination, we may need a valid block3074// that dominates all the rest to insert range predicates.3075BlockBegin* new_header_block;3076if (std_entry->number_of_preds() > 0 || count_invocations() || count_backedges() || RangeCheckElimination) {3077new_header_block = header_block(std_entry, BlockBegin::std_entry_flag, state);3078} else {3079new_header_block = std_entry;3080}30813082// setup start block (root for the IR graph)3083Base* base =3084new Base(3085new_header_block,3086osr_entry3087);3088start->set_next(base, 0);3089start->set_end(base);3090// create & setup state for start block3091start->set_state(state->copy(ValueStack::StateAfter, std_entry->bci()));3092base->set_state(state->copy(ValueStack::StateAfter, std_entry->bci()));30933094if (base->std_entry()->state() == NULL) {3095// setup states for header blocks3096base->std_entry()->merge(state);3097}30983099assert(base->std_entry()->state() != NULL, "");3100return start;3101}310231033104void GraphBuilder::setup_osr_entry_block() {3105assert(compilation()->is_osr_compile(), "only for osrs");31063107int osr_bci = compilation()->osr_bci();3108ciBytecodeStream s(method());3109s.reset_to_bci(osr_bci);3110s.next();3111scope_data()->set_stream(&s);31123113// create a new block to be the osr setup code3114_osr_entry = new BlockBegin(osr_bci);3115_osr_entry->set(BlockBegin::osr_entry_flag);3116_osr_entry->set_depth_first_number(0);3117BlockBegin* target = bci2block()->at(osr_bci);3118assert(target != NULL && target->is_set(BlockBegin::osr_entry_flag), "must be there");3119// the osr entry has no values for locals3120ValueStack* state = target->state()->copy();3121_osr_entry->set_state(state);31223123kill_all();3124_block = _osr_entry;3125_state = _osr_entry->state()->copy();3126assert(_state->bci() == osr_bci, "mismatch");3127_last = _osr_entry;3128Value e = append(new OsrEntry());3129e->set_needs_null_check(false);31303131// OSR buffer is3132//3133// locals[nlocals-1..0]3134// monitors[number_of_locks-1..0]3135//3136// locals is a direct copy of the interpreter frame so in the osr buffer3137// so first slot in the local array is the last local from the interpreter3138// and last slot is local[0] (receiver) from the interpreter3139//3140// Similarly with locks. The first lock slot in the osr buffer is the nth lock3141// from the interpreter frame, the nth lock slot in the osr buffer is 0th lock3142// in the interpreter frame (the method lock if a sync method)31433144// Initialize monitors in the compiled activation.31453146int index;3147Value local;31483149// find all the locals that the interpreter thinks contain live oops3150const ResourceBitMap live_oops = method()->live_local_oops_at_bci(osr_bci);31513152// compute the offset into the locals so that we can treat the buffer3153// as if the locals were still in the interpreter frame3154int locals_offset = BytesPerWord * (method()->max_locals() - 1);3155for_each_local_value(state, index, local) {3156int offset = locals_offset - (index + local->type()->size() - 1) * BytesPerWord;3157Value get;3158if (local->type()->is_object_kind() && !live_oops.at(index)) {3159// The interpreter thinks this local is dead but the compiler3160// doesn't so pretend that the interpreter passed in null.3161get = append(new Constant(objectNull));3162} else {3163get = append(new UnsafeGetRaw(as_BasicType(local->type()), e,3164append(new Constant(new IntConstant(offset))),31650,3166true /*unaligned*/, true /*wide*/));3167}3168_state->store_local(index, get);3169}31703171// the storage for the OSR buffer is freed manually in the LIRGenerator.31723173assert(state->caller_state() == NULL, "should be top scope");3174state->clear_locals();3175Goto* g = new Goto(target, false);3176append(g);3177_osr_entry->set_end(g);3178target->merge(_osr_entry->end()->state());31793180scope_data()->set_stream(NULL);3181}318231833184ValueStack* GraphBuilder::state_at_entry() {3185ValueStack* state = new ValueStack(scope(), NULL);31863187// Set up locals for receiver3188int idx = 0;3189if (!method()->is_static()) {3190// we should always see the receiver3191state->store_local(idx, new Local(method()->holder(), objectType, idx, true));3192idx = 1;3193}31943195// Set up locals for incoming arguments3196ciSignature* sig = method()->signature();3197for (int i = 0; i < sig->count(); i++) {3198ciType* type = sig->type_at(i);3199BasicType basic_type = type->basic_type();3200// don't allow T_ARRAY to propagate into locals types3201if (is_reference_type(basic_type)) basic_type = T_OBJECT;3202ValueType* vt = as_ValueType(basic_type);3203state->store_local(idx, new Local(type, vt, idx, false));3204idx += type->size();3205}32063207// lock synchronized method3208if (method()->is_synchronized()) {3209state->lock(NULL);3210}32113212return state;3213}321432153216GraphBuilder::GraphBuilder(Compilation* compilation, IRScope* scope)3217: _scope_data(NULL)3218, _compilation(compilation)3219, _memory(new MemoryBuffer())3220, _inline_bailout_msg(NULL)3221, _instruction_count(0)3222, _osr_entry(NULL)3223{3224int osr_bci = compilation->osr_bci();32253226// determine entry points and bci2block mapping3227BlockListBuilder blm(compilation, scope, osr_bci);3228CHECK_BAILOUT();32293230BlockList* bci2block = blm.bci2block();3231BlockBegin* start_block = bci2block->at(0);32323233push_root_scope(scope, bci2block, start_block);32343235// setup state for std entry3236_initial_state = state_at_entry();3237start_block->merge(_initial_state);32383239// complete graph3240_vmap = new ValueMap();3241switch (scope->method()->intrinsic_id()) {3242case vmIntrinsics::_dabs : // fall through3243case vmIntrinsics::_dsqrt : // fall through3244case vmIntrinsics::_dsin : // fall through3245case vmIntrinsics::_dcos : // fall through3246case vmIntrinsics::_dtan : // fall through3247case vmIntrinsics::_dlog : // fall through3248case vmIntrinsics::_dlog10 : // fall through3249case vmIntrinsics::_dexp : // fall through3250case vmIntrinsics::_dpow : // fall through3251{3252// Compiles where the root method is an intrinsic need a special3253// compilation environment because the bytecodes for the method3254// shouldn't be parsed during the compilation, only the special3255// Intrinsic node should be emitted. If this isn't done the the3256// code for the inlined version will be different than the root3257// compiled version which could lead to monotonicity problems on3258// intel.3259if (CheckIntrinsics && !scope->method()->intrinsic_candidate()) {3260BAILOUT("failed to inline intrinsic, method not annotated");3261}32623263// Set up a stream so that appending instructions works properly.3264ciBytecodeStream s(scope->method());3265s.reset_to_bci(0);3266scope_data()->set_stream(&s);3267s.next();32683269// setup the initial block state3270_block = start_block;3271_state = start_block->state()->copy_for_parsing();3272_last = start_block;3273load_local(doubleType, 0);3274if (scope->method()->intrinsic_id() == vmIntrinsics::_dpow) {3275load_local(doubleType, 2);3276}32773278// Emit the intrinsic node.3279bool result = try_inline_intrinsics(scope->method());3280if (!result) BAILOUT("failed to inline intrinsic");3281method_return(dpop());32823283// connect the begin and end blocks and we're all done.3284BlockEnd* end = last()->as_BlockEnd();3285block()->set_end(end);3286break;3287}32883289case vmIntrinsics::_Reference_get:3290{3291{3292// With java.lang.ref.reference.get() we must go through the3293// intrinsic - when G1 is enabled - even when get() is the root3294// method of the compile so that, if necessary, the value in3295// the referent field of the reference object gets recorded by3296// the pre-barrier code.3297// Specifically, if G1 is enabled, the value in the referent3298// field is recorded by the G1 SATB pre barrier. This will3299// result in the referent being marked live and the reference3300// object removed from the list of discovered references during3301// reference processing.3302if (CheckIntrinsics && !scope->method()->intrinsic_candidate()) {3303BAILOUT("failed to inline intrinsic, method not annotated");3304}33053306// Also we need intrinsic to prevent commoning reads from this field3307// across safepoint since GC can change its value.33083309// Set up a stream so that appending instructions works properly.3310ciBytecodeStream s(scope->method());3311s.reset_to_bci(0);3312scope_data()->set_stream(&s);3313s.next();33143315// setup the initial block state3316_block = start_block;3317_state = start_block->state()->copy_for_parsing();3318_last = start_block;3319load_local(objectType, 0);33203321// Emit the intrinsic node.3322bool result = try_inline_intrinsics(scope->method());3323if (!result) BAILOUT("failed to inline intrinsic");3324method_return(apop());33253326// connect the begin and end blocks and we're all done.3327BlockEnd* end = last()->as_BlockEnd();3328block()->set_end(end);3329break;3330}3331// Otherwise, fall thru3332}33333334default:3335scope_data()->add_to_work_list(start_block);3336iterate_all_blocks();3337break;3338}3339CHECK_BAILOUT();33403341_start = setup_start_block(osr_bci, start_block, _osr_entry, _initial_state);33423343eliminate_redundant_phis(_start);33443345NOT_PRODUCT(if (PrintValueNumbering && Verbose) print_stats());3346// for osr compile, bailout if some requirements are not fulfilled3347if (osr_bci != -1) {3348BlockBegin* osr_block = blm.bci2block()->at(osr_bci);3349if (!osr_block->is_set(BlockBegin::was_visited_flag)) {3350BAILOUT("osr entry must have been visited for osr compile");3351}33523353// check if osr entry point has empty stack - we cannot handle non-empty stacks at osr entry points3354if (!osr_block->state()->stack_is_empty()) {3355BAILOUT("stack not empty at OSR entry point");3356}3357}3358#ifndef PRODUCT3359if (PrintCompilation && Verbose) tty->print_cr("Created %d Instructions", _instruction_count);3360#endif3361}336233633364ValueStack* GraphBuilder::copy_state_before() {3365return copy_state_before_with_bci(bci());3366}33673368ValueStack* GraphBuilder::copy_state_exhandling() {3369return copy_state_exhandling_with_bci(bci());3370}33713372ValueStack* GraphBuilder::copy_state_for_exception() {3373return copy_state_for_exception_with_bci(bci());3374}33753376ValueStack* GraphBuilder::copy_state_before_with_bci(int bci) {3377return state()->copy(ValueStack::StateBefore, bci);3378}33793380ValueStack* GraphBuilder::copy_state_exhandling_with_bci(int bci) {3381if (!has_handler()) return NULL;3382return state()->copy(ValueStack::StateBefore, bci);3383}33843385ValueStack* GraphBuilder::copy_state_for_exception_with_bci(int bci) {3386ValueStack* s = copy_state_exhandling_with_bci(bci);3387if (s == NULL) {3388if (_compilation->env()->should_retain_local_variables()) {3389s = state()->copy(ValueStack::ExceptionState, bci);3390} else {3391s = state()->copy(ValueStack::EmptyExceptionState, bci);3392}3393}3394return s;3395}33963397int GraphBuilder::recursive_inline_level(ciMethod* cur_callee) const {3398int recur_level = 0;3399for (IRScope* s = scope(); s != NULL; s = s->caller()) {3400if (s->method() == cur_callee) {3401++recur_level;3402}3403}3404return recur_level;3405}340634073408bool GraphBuilder::try_inline(ciMethod* callee, bool holder_known, bool ignore_return, Bytecodes::Code bc, Value receiver) {3409const char* msg = NULL;34103411// clear out any existing inline bailout condition3412clear_inline_bailout();34133414// exclude methods we don't want to inline3415msg = should_not_inline(callee);3416if (msg != NULL) {3417print_inlining(callee, msg, /*success*/ false);3418return false;3419}34203421// method handle invokes3422if (callee->is_method_handle_intrinsic()) {3423if (try_method_handle_inline(callee, ignore_return)) {3424if (callee->has_reserved_stack_access()) {3425compilation()->set_has_reserved_stack_access(true);3426}3427return true;3428}3429return false;3430}34313432// handle intrinsics3433if (callee->intrinsic_id() != vmIntrinsics::_none &&3434callee->check_intrinsic_candidate()) {3435if (try_inline_intrinsics(callee, ignore_return)) {3436print_inlining(callee, "intrinsic");3437if (callee->has_reserved_stack_access()) {3438compilation()->set_has_reserved_stack_access(true);3439}3440return true;3441}3442// try normal inlining3443}34443445// certain methods cannot be parsed at all3446msg = check_can_parse(callee);3447if (msg != NULL) {3448print_inlining(callee, msg, /*success*/ false);3449return false;3450}34513452// If bytecode not set use the current one.3453if (bc == Bytecodes::_illegal) {3454bc = code();3455}3456if (try_inline_full(callee, holder_known, ignore_return, bc, receiver)) {3457if (callee->has_reserved_stack_access()) {3458compilation()->set_has_reserved_stack_access(true);3459}3460return true;3461}34623463// Entire compilation could fail during try_inline_full call.3464// In that case printing inlining decision info is useless.3465if (!bailed_out())3466print_inlining(callee, _inline_bailout_msg, /*success*/ false);34673468return false;3469}347034713472const char* GraphBuilder::check_can_parse(ciMethod* callee) const {3473// Certain methods cannot be parsed at all:3474if ( callee->is_native()) return "native method";3475if ( callee->is_abstract()) return "abstract method";3476if (!callee->can_be_parsed()) return "cannot be parsed";3477return NULL;3478}34793480// negative filter: should callee NOT be inlined? returns NULL, ok to inline, or rejection msg3481const char* GraphBuilder::should_not_inline(ciMethod* callee) const {3482if ( compilation()->directive()->should_not_inline(callee)) return "disallowed by CompileCommand";3483if ( callee->dont_inline()) return "don't inline by annotation";3484return NULL;3485}34863487void GraphBuilder::build_graph_for_intrinsic(ciMethod* callee, bool ignore_return) {3488vmIntrinsics::ID id = callee->intrinsic_id();3489assert(id != vmIntrinsics::_none, "must be a VM intrinsic");34903491// Some intrinsics need special IR nodes.3492switch(id) {3493case vmIntrinsics::_getReference : append_unsafe_get_obj(callee, T_OBJECT, false); return;3494case vmIntrinsics::_getBoolean : append_unsafe_get_obj(callee, T_BOOLEAN, false); return;3495case vmIntrinsics::_getByte : append_unsafe_get_obj(callee, T_BYTE, false); return;3496case vmIntrinsics::_getShort : append_unsafe_get_obj(callee, T_SHORT, false); return;3497case vmIntrinsics::_getChar : append_unsafe_get_obj(callee, T_CHAR, false); return;3498case vmIntrinsics::_getInt : append_unsafe_get_obj(callee, T_INT, false); return;3499case vmIntrinsics::_getLong : append_unsafe_get_obj(callee, T_LONG, false); return;3500case vmIntrinsics::_getFloat : append_unsafe_get_obj(callee, T_FLOAT, false); return;3501case vmIntrinsics::_getDouble : append_unsafe_get_obj(callee, T_DOUBLE, false); return;3502case vmIntrinsics::_putReference : append_unsafe_put_obj(callee, T_OBJECT, false); return;3503case vmIntrinsics::_putBoolean : append_unsafe_put_obj(callee, T_BOOLEAN, false); return;3504case vmIntrinsics::_putByte : append_unsafe_put_obj(callee, T_BYTE, false); return;3505case vmIntrinsics::_putShort : append_unsafe_put_obj(callee, T_SHORT, false); return;3506case vmIntrinsics::_putChar : append_unsafe_put_obj(callee, T_CHAR, false); return;3507case vmIntrinsics::_putInt : append_unsafe_put_obj(callee, T_INT, false); return;3508case vmIntrinsics::_putLong : append_unsafe_put_obj(callee, T_LONG, false); return;3509case vmIntrinsics::_putFloat : append_unsafe_put_obj(callee, T_FLOAT, false); return;3510case vmIntrinsics::_putDouble : append_unsafe_put_obj(callee, T_DOUBLE, false); return;3511case vmIntrinsics::_getShortUnaligned : append_unsafe_get_obj(callee, T_SHORT, false); return;3512case vmIntrinsics::_getCharUnaligned : append_unsafe_get_obj(callee, T_CHAR, false); return;3513case vmIntrinsics::_getIntUnaligned : append_unsafe_get_obj(callee, T_INT, false); return;3514case vmIntrinsics::_getLongUnaligned : append_unsafe_get_obj(callee, T_LONG, false); return;3515case vmIntrinsics::_putShortUnaligned : append_unsafe_put_obj(callee, T_SHORT, false); return;3516case vmIntrinsics::_putCharUnaligned : append_unsafe_put_obj(callee, T_CHAR, false); return;3517case vmIntrinsics::_putIntUnaligned : append_unsafe_put_obj(callee, T_INT, false); return;3518case vmIntrinsics::_putLongUnaligned : append_unsafe_put_obj(callee, T_LONG, false); return;3519case vmIntrinsics::_getReferenceVolatile : append_unsafe_get_obj(callee, T_OBJECT, true); return;3520case vmIntrinsics::_getBooleanVolatile : append_unsafe_get_obj(callee, T_BOOLEAN, true); return;3521case vmIntrinsics::_getByteVolatile : append_unsafe_get_obj(callee, T_BYTE, true); return;3522case vmIntrinsics::_getShortVolatile : append_unsafe_get_obj(callee, T_SHORT, true); return;3523case vmIntrinsics::_getCharVolatile : append_unsafe_get_obj(callee, T_CHAR, true); return;3524case vmIntrinsics::_getIntVolatile : append_unsafe_get_obj(callee, T_INT, true); return;3525case vmIntrinsics::_getLongVolatile : append_unsafe_get_obj(callee, T_LONG, true); return;3526case vmIntrinsics::_getFloatVolatile : append_unsafe_get_obj(callee, T_FLOAT, true); return;3527case vmIntrinsics::_getDoubleVolatile : append_unsafe_get_obj(callee, T_DOUBLE, true); return;3528case vmIntrinsics::_putReferenceVolatile : append_unsafe_put_obj(callee, T_OBJECT, true); return;3529case vmIntrinsics::_putBooleanVolatile : append_unsafe_put_obj(callee, T_BOOLEAN, true); return;3530case vmIntrinsics::_putByteVolatile : append_unsafe_put_obj(callee, T_BYTE, true); return;3531case vmIntrinsics::_putShortVolatile : append_unsafe_put_obj(callee, T_SHORT, true); return;3532case vmIntrinsics::_putCharVolatile : append_unsafe_put_obj(callee, T_CHAR, true); return;3533case vmIntrinsics::_putIntVolatile : append_unsafe_put_obj(callee, T_INT, true); return;3534case vmIntrinsics::_putLongVolatile : append_unsafe_put_obj(callee, T_LONG, true); return;3535case vmIntrinsics::_putFloatVolatile : append_unsafe_put_obj(callee, T_FLOAT, true); return;3536case vmIntrinsics::_putDoubleVolatile : append_unsafe_put_obj(callee, T_DOUBLE, true); return;3537case vmIntrinsics::_compareAndSetLong:3538case vmIntrinsics::_compareAndSetInt:3539case vmIntrinsics::_compareAndSetReference : append_unsafe_CAS(callee); return;3540case vmIntrinsics::_getAndAddInt:3541case vmIntrinsics::_getAndAddLong : append_unsafe_get_and_set_obj(callee, true); return;3542case vmIntrinsics::_getAndSetInt :3543case vmIntrinsics::_getAndSetLong :3544case vmIntrinsics::_getAndSetReference : append_unsafe_get_and_set_obj(callee, false); return;3545case vmIntrinsics::_getCharStringU : append_char_access(callee, false); return;3546case vmIntrinsics::_putCharStringU : append_char_access(callee, true); return;3547default:3548break;3549}35503551// create intrinsic node3552const bool has_receiver = !callee->is_static();3553ValueType* result_type = as_ValueType(callee->return_type());3554ValueStack* state_before = copy_state_for_exception();35553556Values* args = state()->pop_arguments(callee->arg_size());35573558if (is_profiling()) {3559// Don't profile in the special case where the root method3560// is the intrinsic3561if (callee != method()) {3562// Note that we'd collect profile data in this method if we wanted it.3563compilation()->set_would_profile(true);3564if (profile_calls()) {3565Value recv = NULL;3566if (has_receiver) {3567recv = args->at(0);3568null_check(recv);3569}3570profile_call(callee, recv, NULL, collect_args_for_profiling(args, callee, true), true);3571}3572}3573}35743575Intrinsic* result = new Intrinsic(result_type, callee->intrinsic_id(),3576args, has_receiver, state_before,3577vmIntrinsics::preserves_state(id),3578vmIntrinsics::can_trap(id));3579// append instruction & push result3580Value value = append_split(result);3581if (result_type != voidType && !ignore_return) {3582push(result_type, value);3583}35843585if (callee != method() && profile_return() && result_type->is_object_kind()) {3586profile_return_type(result, callee);3587}3588}35893590bool GraphBuilder::try_inline_intrinsics(ciMethod* callee, bool ignore_return) {3591// For calling is_intrinsic_available we need to transition to3592// the '_thread_in_vm' state because is_intrinsic_available()3593// accesses critical VM-internal data.3594bool is_available = false;3595{3596VM_ENTRY_MARK;3597methodHandle mh(THREAD, callee->get_Method());3598is_available = _compilation->compiler()->is_intrinsic_available(mh, _compilation->directive());3599}36003601if (!is_available) {3602if (!InlineNatives) {3603// Return false and also set message that the inlining of3604// intrinsics has been disabled in general.3605INLINE_BAILOUT("intrinsic method inlining disabled");3606} else {3607return false;3608}3609}3610build_graph_for_intrinsic(callee, ignore_return);3611return true;3612}361336143615bool GraphBuilder::try_inline_jsr(int jsr_dest_bci) {3616// Introduce a new callee continuation point - all Ret instructions3617// will be replaced with Gotos to this point.3618BlockBegin* cont = block_at(next_bci());3619assert(cont != NULL, "continuation must exist (BlockListBuilder starts a new block after a jsr");36203621// Note: can not assign state to continuation yet, as we have to3622// pick up the state from the Ret instructions.36233624// Push callee scope3625push_scope_for_jsr(cont, jsr_dest_bci);36263627// Temporarily set up bytecode stream so we can append instructions3628// (only using the bci of this stream)3629scope_data()->set_stream(scope_data()->parent()->stream());36303631BlockBegin* jsr_start_block = block_at(jsr_dest_bci);3632assert(jsr_start_block != NULL, "jsr start block must exist");3633assert(!jsr_start_block->is_set(BlockBegin::was_visited_flag), "should not have visited jsr yet");3634Goto* goto_sub = new Goto(jsr_start_block, false);3635// Must copy state to avoid wrong sharing when parsing bytecodes3636assert(jsr_start_block->state() == NULL, "should have fresh jsr starting block");3637jsr_start_block->set_state(copy_state_before_with_bci(jsr_dest_bci));3638append(goto_sub);3639_block->set_end(goto_sub);3640_last = _block = jsr_start_block;36413642// Clear out bytecode stream3643scope_data()->set_stream(NULL);36443645scope_data()->add_to_work_list(jsr_start_block);36463647// Ready to resume parsing in subroutine3648iterate_all_blocks();36493650// If we bailed out during parsing, return immediately (this is bad news)3651CHECK_BAILOUT_(false);36523653// Detect whether the continuation can actually be reached. If not,3654// it has not had state set by the join() operations in3655// iterate_bytecodes_for_block()/ret() and we should not touch the3656// iteration state. The calling activation of3657// iterate_bytecodes_for_block will then complete normally.3658if (cont->state() != NULL) {3659if (!cont->is_set(BlockBegin::was_visited_flag)) {3660// add continuation to work list instead of parsing it immediately3661scope_data()->parent()->add_to_work_list(cont);3662}3663}36643665assert(jsr_continuation() == cont, "continuation must not have changed");3666assert(!jsr_continuation()->is_set(BlockBegin::was_visited_flag) ||3667jsr_continuation()->is_set(BlockBegin::parser_loop_header_flag),3668"continuation can only be visited in case of backward branches");3669assert(_last && _last->as_BlockEnd(), "block must have end");36703671// continuation is in work list, so end iteration of current block3672_skip_block = true;3673pop_scope_for_jsr();36743675return true;3676}367736783679// Inline the entry of a synchronized method as a monitor enter and3680// register the exception handler which releases the monitor if an3681// exception is thrown within the callee. Note that the monitor enter3682// cannot throw an exception itself, because the receiver is3683// guaranteed to be non-null by the explicit null check at the3684// beginning of inlining.3685void GraphBuilder::inline_sync_entry(Value lock, BlockBegin* sync_handler) {3686assert(lock != NULL && sync_handler != NULL, "lock or handler missing");36873688monitorenter(lock, SynchronizationEntryBCI);3689assert(_last->as_MonitorEnter() != NULL, "monitor enter expected");3690_last->set_needs_null_check(false);36913692sync_handler->set(BlockBegin::exception_entry_flag);3693sync_handler->set(BlockBegin::is_on_work_list_flag);36943695ciExceptionHandler* desc = new ciExceptionHandler(method()->holder(), 0, method()->code_size(), -1, 0);3696XHandler* h = new XHandler(desc);3697h->set_entry_block(sync_handler);3698scope_data()->xhandlers()->append(h);3699scope_data()->set_has_handler();3700}370137023703// If an exception is thrown and not handled within an inlined3704// synchronized method, the monitor must be released before the3705// exception is rethrown in the outer scope. Generate the appropriate3706// instructions here.3707void GraphBuilder::fill_sync_handler(Value lock, BlockBegin* sync_handler, bool default_handler) {3708BlockBegin* orig_block = _block;3709ValueStack* orig_state = _state;3710Instruction* orig_last = _last;3711_last = _block = sync_handler;3712_state = sync_handler->state()->copy();37133714assert(sync_handler != NULL, "handler missing");3715assert(!sync_handler->is_set(BlockBegin::was_visited_flag), "is visited here");37163717assert(lock != NULL || default_handler, "lock or handler missing");37183719XHandler* h = scope_data()->xhandlers()->remove_last();3720assert(h->entry_block() == sync_handler, "corrupt list of handlers");37213722block()->set(BlockBegin::was_visited_flag);3723Value exception = append_with_bci(new ExceptionObject(), SynchronizationEntryBCI);3724assert(exception->is_pinned(), "must be");37253726int bci = SynchronizationEntryBCI;3727if (compilation()->env()->dtrace_method_probes()) {3728// Report exit from inline methods. We don't have a stream here3729// so pass an explicit bci of SynchronizationEntryBCI.3730Values* args = new Values(1);3731args->push(append_with_bci(new Constant(new MethodConstant(method())), bci));3732append_with_bci(new RuntimeCall(voidType, "dtrace_method_exit", CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit), args), bci);3733}37343735if (lock) {3736assert(state()->locks_size() > 0 && state()->lock_at(state()->locks_size() - 1) == lock, "lock is missing");3737if (!lock->is_linked()) {3738lock = append_with_bci(lock, bci);3739}37403741// exit the monitor in the context of the synchronized method3742monitorexit(lock, bci);37433744// exit the context of the synchronized method3745if (!default_handler) {3746pop_scope();3747bci = _state->caller_state()->bci();3748_state = _state->caller_state()->copy_for_parsing();3749}3750}37513752// perform the throw as if at the the call site3753apush(exception);3754throw_op(bci);37553756BlockEnd* end = last()->as_BlockEnd();3757block()->set_end(end);37583759_block = orig_block;3760_state = orig_state;3761_last = orig_last;3762}376337643765bool GraphBuilder::try_inline_full(ciMethod* callee, bool holder_known, bool ignore_return, Bytecodes::Code bc, Value receiver) {3766assert(!callee->is_native(), "callee must not be native");3767if (CompilationPolicy::should_not_inline(compilation()->env(), callee)) {3768INLINE_BAILOUT("inlining prohibited by policy");3769}3770// first perform tests of things it's not possible to inline3771if (callee->has_exception_handlers() &&3772!InlineMethodsWithExceptionHandlers) INLINE_BAILOUT("callee has exception handlers");3773if (callee->is_synchronized() &&3774!InlineSynchronizedMethods ) INLINE_BAILOUT("callee is synchronized");3775if (!callee->holder()->is_linked()) INLINE_BAILOUT("callee's klass not linked yet");3776if (bc == Bytecodes::_invokestatic &&3777!callee->holder()->is_initialized()) INLINE_BAILOUT("callee's klass not initialized yet");3778if (!callee->has_balanced_monitors()) INLINE_BAILOUT("callee's monitors do not match");37793780// Proper inlining of methods with jsrs requires a little more work.3781if (callee->has_jsrs() ) INLINE_BAILOUT("jsrs not handled properly by inliner yet");37823783if (is_profiling() && !callee->ensure_method_data()) {3784INLINE_BAILOUT("mdo allocation failed");3785}37863787const bool is_invokedynamic = (bc == Bytecodes::_invokedynamic);3788const bool has_receiver = (bc != Bytecodes::_invokestatic && !is_invokedynamic);37893790const int args_base = state()->stack_size() - callee->arg_size();3791assert(args_base >= 0, "stack underflow during inlining");37923793Value recv = NULL;3794if (has_receiver) {3795assert(!callee->is_static(), "callee must not be static");3796assert(callee->arg_size() > 0, "must have at least a receiver");37973798recv = state()->stack_at(args_base);3799if (recv->is_null_obj()) {3800INLINE_BAILOUT("receiver is always null");3801}3802}38033804// now perform tests that are based on flag settings3805bool inlinee_by_directive = compilation()->directive()->should_inline(callee);3806if (callee->force_inline() || inlinee_by_directive) {3807if (inline_level() > MaxForceInlineLevel ) INLINE_BAILOUT("MaxForceInlineLevel");3808if (recursive_inline_level(callee) > C1MaxRecursiveInlineLevel) INLINE_BAILOUT("recursive inlining too deep");38093810const char* msg = "";3811if (callee->force_inline()) msg = "force inline by annotation";3812if (inlinee_by_directive) msg = "force inline by CompileCommand";3813print_inlining(callee, msg);3814} else {3815// use heuristic controls on inlining3816if (inline_level() > C1MaxInlineLevel ) INLINE_BAILOUT("inlining too deep");3817int callee_recursive_level = recursive_inline_level(callee);3818if (callee_recursive_level > C1MaxRecursiveInlineLevel ) INLINE_BAILOUT("recursive inlining too deep");3819if (callee->code_size_for_inlining() > max_inline_size() ) INLINE_BAILOUT("callee is too large");3820// Additional condition to limit stack usage for non-recursive calls.3821if ((callee_recursive_level == 0) &&3822(callee->max_stack() + callee->max_locals() - callee->size_of_parameters() > C1InlineStackLimit)) {3823INLINE_BAILOUT("callee uses too much stack");3824}38253826// don't inline throwable methods unless the inlining tree is rooted in a throwable class3827if (callee->name() == ciSymbols::object_initializer_name() &&3828callee->holder()->is_subclass_of(ciEnv::current()->Throwable_klass())) {3829// Throwable constructor call3830IRScope* top = scope();3831while (top->caller() != NULL) {3832top = top->caller();3833}3834if (!top->method()->holder()->is_subclass_of(ciEnv::current()->Throwable_klass())) {3835INLINE_BAILOUT("don't inline Throwable constructors");3836}3837}38383839if (compilation()->env()->num_inlined_bytecodes() > DesiredMethodLimit) {3840INLINE_BAILOUT("total inlining greater than DesiredMethodLimit");3841}3842// printing3843print_inlining(callee, "inline", /*success*/ true);3844}38453846assert(bc != Bytecodes::_invokestatic || callee->holder()->is_initialized(), "required");38473848// NOTE: Bailouts from this point on, which occur at the3849// GraphBuilder level, do not cause bailout just of the inlining but3850// in fact of the entire compilation.38513852BlockBegin* orig_block = block();38533854// Insert null check if necessary3855if (has_receiver) {3856// note: null check must happen even if first instruction of callee does3857// an implicit null check since the callee is in a different scope3858// and we must make sure exception handling does the right thing3859null_check(recv);3860}38613862if (is_profiling()) {3863// Note that we'd collect profile data in this method if we wanted it.3864// this may be redundant here...3865compilation()->set_would_profile(true);38663867if (profile_calls()) {3868int start = 0;3869Values* obj_args = args_list_for_profiling(callee, start, has_receiver);3870if (obj_args != NULL) {3871int s = obj_args->max_length();3872// if called through method handle invoke, some arguments may have been popped3873for (int i = args_base+start, j = 0; j < obj_args->max_length() && i < state()->stack_size(); ) {3874Value v = state()->stack_at_inc(i);3875if (v->type()->is_object_kind()) {3876obj_args->push(v);3877j++;3878}3879}3880check_args_for_profiling(obj_args, s);3881}3882profile_call(callee, recv, holder_known ? callee->holder() : NULL, obj_args, true);3883}3884}38853886// Introduce a new callee continuation point - if the callee has3887// more than one return instruction or the return does not allow3888// fall-through of control flow, all return instructions of the3889// callee will need to be replaced by Goto's pointing to this3890// continuation point.3891BlockBegin* cont = block_at(next_bci());3892bool continuation_existed = true;3893if (cont == NULL) {3894cont = new BlockBegin(next_bci());3895// low number so that continuation gets parsed as early as possible3896cont->set_depth_first_number(0);3897if (PrintInitialBlockList) {3898tty->print_cr("CFG: created block %d (bci %d) as continuation for inline at bci %d",3899cont->block_id(), cont->bci(), bci());3900}3901continuation_existed = false;3902}3903// Record number of predecessors of continuation block before3904// inlining, to detect if inlined method has edges to its3905// continuation after inlining.3906int continuation_preds = cont->number_of_preds();39073908// Push callee scope3909push_scope(callee, cont);39103911// the BlockListBuilder for the callee could have bailed out3912if (bailed_out())3913return false;39143915// Temporarily set up bytecode stream so we can append instructions3916// (only using the bci of this stream)3917scope_data()->set_stream(scope_data()->parent()->stream());39183919// Pass parameters into callee state: add assignments3920// note: this will also ensure that all arguments are computed before being passed3921ValueStack* callee_state = state();3922ValueStack* caller_state = state()->caller_state();3923for (int i = args_base; i < caller_state->stack_size(); ) {3924const int arg_no = i - args_base;3925Value arg = caller_state->stack_at_inc(i);3926store_local(callee_state, arg, arg_no);3927}39283929// Remove args from stack.3930// Note that we preserve locals state in case we can use it later3931// (see use of pop_scope() below)3932caller_state->truncate_stack(args_base);3933assert(callee_state->stack_size() == 0, "callee stack must be empty");39343935Value lock = NULL;3936BlockBegin* sync_handler = NULL;39373938// Inline the locking of the receiver if the callee is synchronized3939if (callee->is_synchronized()) {3940lock = callee->is_static() ? append(new Constant(new InstanceConstant(callee->holder()->java_mirror())))3941: state()->local_at(0);3942sync_handler = new BlockBegin(SynchronizationEntryBCI);3943inline_sync_entry(lock, sync_handler);3944}39453946if (compilation()->env()->dtrace_method_probes()) {3947Values* args = new Values(1);3948args->push(append(new Constant(new MethodConstant(method()))));3949append(new RuntimeCall(voidType, "dtrace_method_entry", CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry), args));3950}39513952if (profile_inlined_calls()) {3953profile_invocation(callee, copy_state_before_with_bci(SynchronizationEntryBCI));3954}39553956BlockBegin* callee_start_block = block_at(0);3957if (callee_start_block != NULL) {3958assert(callee_start_block->is_set(BlockBegin::parser_loop_header_flag), "must be loop header");3959Goto* goto_callee = new Goto(callee_start_block, false);3960// The state for this goto is in the scope of the callee, so use3961// the entry bci for the callee instead of the call site bci.3962append_with_bci(goto_callee, 0);3963_block->set_end(goto_callee);3964callee_start_block->merge(callee_state);39653966_last = _block = callee_start_block;39673968scope_data()->add_to_work_list(callee_start_block);3969}39703971// Clear out bytecode stream3972scope_data()->set_stream(NULL);3973scope_data()->set_ignore_return(ignore_return);39743975CompileLog* log = compilation()->log();3976if (log != NULL) log->head("parse method='%d'", log->identify(callee));39773978// Ready to resume parsing in callee (either in the same block we3979// were in before or in the callee's start block)3980iterate_all_blocks(callee_start_block == NULL);39813982if (log != NULL) log->done("parse");39833984// If we bailed out during parsing, return immediately (this is bad news)3985if (bailed_out())3986return false;39873988// iterate_all_blocks theoretically traverses in random order; in3989// practice, we have only traversed the continuation if we are3990// inlining into a subroutine3991assert(continuation_existed ||3992!continuation()->is_set(BlockBegin::was_visited_flag),3993"continuation should not have been parsed yet if we created it");39943995// At this point we are almost ready to return and resume parsing of3996// the caller back in the GraphBuilder. The only thing we want to do3997// first is an optimization: during parsing of the callee we3998// generated at least one Goto to the continuation block. If we3999// generated exactly one, and if the inlined method spanned exactly4000// one block (and we didn't have to Goto its entry), then we snip4001// off the Goto to the continuation, allowing control to fall4002// through back into the caller block and effectively performing4003// block merging. This allows load elimination and CSE to take place4004// across multiple callee scopes if they are relatively simple, and4005// is currently essential to making inlining profitable.4006if (num_returns() == 14007&& block() == orig_block4008&& block() == inline_cleanup_block()) {4009_last = inline_cleanup_return_prev();4010_state = inline_cleanup_state();4011} else if (continuation_preds == cont->number_of_preds()) {4012// Inlining caused that the instructions after the invoke in the4013// caller are not reachable any more. So skip filling this block4014// with instructions!4015assert(cont == continuation(), "");4016assert(_last && _last->as_BlockEnd(), "");4017_skip_block = true;4018} else {4019// Resume parsing in continuation block unless it was already parsed.4020// Note that if we don't change _last here, iteration in4021// iterate_bytecodes_for_block will stop when we return.4022if (!continuation()->is_set(BlockBegin::was_visited_flag)) {4023// add continuation to work list instead of parsing it immediately4024assert(_last && _last->as_BlockEnd(), "");4025scope_data()->parent()->add_to_work_list(continuation());4026_skip_block = true;4027}4028}40294030// Fill the exception handler for synchronized methods with instructions4031if (callee->is_synchronized() && sync_handler->state() != NULL) {4032fill_sync_handler(lock, sync_handler);4033} else {4034pop_scope();4035}40364037compilation()->notice_inlined_method(callee);40384039return true;4040}404140424043bool GraphBuilder::try_method_handle_inline(ciMethod* callee, bool ignore_return) {4044ValueStack* state_before = copy_state_before();4045vmIntrinsics::ID iid = callee->intrinsic_id();4046switch (iid) {4047case vmIntrinsics::_invokeBasic:4048{4049// get MethodHandle receiver4050const int args_base = state()->stack_size() - callee->arg_size();4051ValueType* type = state()->stack_at(args_base)->type();4052if (type->is_constant()) {4053ciObject* mh = type->as_ObjectType()->constant_value();4054if (mh->is_method_handle()) {4055ciMethod* target = mh->as_method_handle()->get_vmtarget();40564057// We don't do CHA here so only inline static and statically bindable methods.4058if (target->is_static() || target->can_be_statically_bound()) {4059if (ciMethod::is_consistent_info(callee, target)) {4060Bytecodes::Code bc = target->is_static() ? Bytecodes::_invokestatic : Bytecodes::_invokevirtual;4061ignore_return = ignore_return || (callee->return_type()->is_void() && !target->return_type()->is_void());4062if (try_inline(target, /*holder_known*/ !callee->is_static(), ignore_return, bc)) {4063return true;4064}4065} else {4066print_inlining(target, "signatures mismatch", /*success*/ false);4067}4068} else {4069assert(false, "no inlining through MH::invokeBasic"); // missing optimization opportunity due to suboptimal LF shape4070print_inlining(target, "not static or statically bindable", /*success*/ false);4071}4072} else {4073assert(mh->is_null_object(), "not a null");4074print_inlining(callee, "receiver is always null", /*success*/ false);4075}4076} else {4077print_inlining(callee, "receiver not constant", /*success*/ false);4078}4079}4080break;40814082case vmIntrinsics::_linkToVirtual:4083case vmIntrinsics::_linkToStatic:4084case vmIntrinsics::_linkToSpecial:4085case vmIntrinsics::_linkToInterface:4086{4087// pop MemberName argument4088const int args_base = state()->stack_size() - callee->arg_size();4089ValueType* type = apop()->type();4090if (type->is_constant()) {4091ciMethod* target = type->as_ObjectType()->constant_value()->as_member_name()->get_vmtarget();4092ignore_return = ignore_return || (callee->return_type()->is_void() && !target->return_type()->is_void());4093// If the target is another method handle invoke, try to recursively get4094// a better target.4095if (target->is_method_handle_intrinsic()) {4096if (try_method_handle_inline(target, ignore_return)) {4097return true;4098}4099} else if (!ciMethod::is_consistent_info(callee, target)) {4100print_inlining(target, "signatures mismatch", /*success*/ false);4101} else {4102ciSignature* signature = target->signature();4103const int receiver_skip = target->is_static() ? 0 : 1;4104// Cast receiver to its type.4105if (!target->is_static()) {4106ciKlass* tk = signature->accessing_klass();4107Value obj = state()->stack_at(args_base);4108if (obj->exact_type() == NULL &&4109obj->declared_type() != tk && tk != compilation()->env()->Object_klass()) {4110TypeCast* c = new TypeCast(tk, obj, state_before);4111append(c);4112state()->stack_at_put(args_base, c);4113}4114}4115// Cast reference arguments to its type.4116for (int i = 0, j = 0; i < signature->count(); i++) {4117ciType* t = signature->type_at(i);4118if (t->is_klass()) {4119ciKlass* tk = t->as_klass();4120Value obj = state()->stack_at(args_base + receiver_skip + j);4121if (obj->exact_type() == NULL &&4122obj->declared_type() != tk && tk != compilation()->env()->Object_klass()) {4123TypeCast* c = new TypeCast(t, obj, state_before);4124append(c);4125state()->stack_at_put(args_base + receiver_skip + j, c);4126}4127}4128j += t->size(); // long and double take two slots4129}4130// We don't do CHA here so only inline static and statically bindable methods.4131if (target->is_static() || target->can_be_statically_bound()) {4132Bytecodes::Code bc = target->is_static() ? Bytecodes::_invokestatic : Bytecodes::_invokevirtual;4133if (try_inline(target, /*holder_known*/ !callee->is_static(), ignore_return, bc)) {4134return true;4135}4136} else {4137print_inlining(target, "not static or statically bindable", /*success*/ false);4138}4139}4140} else {4141print_inlining(callee, "MemberName not constant", /*success*/ false);4142}4143}4144break;41454146case vmIntrinsics::_linkToNative:4147break; // TODO: NYI41484149default:4150fatal("unexpected intrinsic %d: %s", vmIntrinsics::as_int(iid), vmIntrinsics::name_at(iid));4151break;4152}4153set_state(state_before->copy_for_parsing());4154return false;4155}415641574158void GraphBuilder::inline_bailout(const char* msg) {4159assert(msg != NULL, "inline bailout msg must exist");4160_inline_bailout_msg = msg;4161}416241634164void GraphBuilder::clear_inline_bailout() {4165_inline_bailout_msg = NULL;4166}416741684169void GraphBuilder::push_root_scope(IRScope* scope, BlockList* bci2block, BlockBegin* start) {4170ScopeData* data = new ScopeData(NULL);4171data->set_scope(scope);4172data->set_bci2block(bci2block);4173_scope_data = data;4174_block = start;4175}417641774178void GraphBuilder::push_scope(ciMethod* callee, BlockBegin* continuation) {4179IRScope* callee_scope = new IRScope(compilation(), scope(), bci(), callee, -1, false);4180scope()->add_callee(callee_scope);41814182BlockListBuilder blb(compilation(), callee_scope, -1);4183CHECK_BAILOUT();41844185if (!blb.bci2block()->at(0)->is_set(BlockBegin::parser_loop_header_flag)) {4186// this scope can be inlined directly into the caller so remove4187// the block at bci 0.4188blb.bci2block()->at_put(0, NULL);4189}41904191set_state(new ValueStack(callee_scope, state()->copy(ValueStack::CallerState, bci())));41924193ScopeData* data = new ScopeData(scope_data());4194data->set_scope(callee_scope);4195data->set_bci2block(blb.bci2block());4196data->set_continuation(continuation);4197_scope_data = data;4198}419942004201void GraphBuilder::push_scope_for_jsr(BlockBegin* jsr_continuation, int jsr_dest_bci) {4202ScopeData* data = new ScopeData(scope_data());4203data->set_parsing_jsr();4204data->set_jsr_entry_bci(jsr_dest_bci);4205data->set_jsr_return_address_local(-1);4206// Must clone bci2block list as we will be mutating it in order to4207// properly clone all blocks in jsr region as well as exception4208// handlers containing rets4209BlockList* new_bci2block = new BlockList(bci2block()->length());4210new_bci2block->appendAll(bci2block());4211data->set_bci2block(new_bci2block);4212data->set_scope(scope());4213data->setup_jsr_xhandlers();4214data->set_continuation(continuation());4215data->set_jsr_continuation(jsr_continuation);4216_scope_data = data;4217}421842194220void GraphBuilder::pop_scope() {4221int number_of_locks = scope()->number_of_locks();4222_scope_data = scope_data()->parent();4223// accumulate minimum number of monitor slots to be reserved4224scope()->set_min_number_of_locks(number_of_locks);4225}422642274228void GraphBuilder::pop_scope_for_jsr() {4229_scope_data = scope_data()->parent();4230}42314232void GraphBuilder::append_unsafe_get_obj(ciMethod* callee, BasicType t, bool is_volatile) {4233Values* args = state()->pop_arguments(callee->arg_size());4234null_check(args->at(0));4235Instruction* offset = args->at(2);4236#ifndef _LP644237offset = append(new Convert(Bytecodes::_l2i, offset, as_ValueType(T_INT)));4238#endif4239Instruction* op = append(new UnsafeGetObject(t, args->at(1), offset, is_volatile));4240push(op->type(), op);4241compilation()->set_has_unsafe_access(true);4242}424342444245void GraphBuilder::append_unsafe_put_obj(ciMethod* callee, BasicType t, bool is_volatile) {4246Values* args = state()->pop_arguments(callee->arg_size());4247null_check(args->at(0));4248Instruction* offset = args->at(2);4249#ifndef _LP644250offset = append(new Convert(Bytecodes::_l2i, offset, as_ValueType(T_INT)));4251#endif4252Value val = args->at(3);4253if (t == T_BOOLEAN) {4254Value mask = append(new Constant(new IntConstant(1)));4255val = append(new LogicOp(Bytecodes::_iand, val, mask));4256}4257Instruction* op = append(new UnsafePutObject(t, args->at(1), offset, val, is_volatile));4258compilation()->set_has_unsafe_access(true);4259kill_all();4260}426142624263void GraphBuilder::append_unsafe_get_raw(ciMethod* callee, BasicType t) {4264Values* args = state()->pop_arguments(callee->arg_size());4265null_check(args->at(0));4266Instruction* op = append(new UnsafeGetRaw(t, args->at(1), false));4267push(op->type(), op);4268compilation()->set_has_unsafe_access(true);4269}427042714272void GraphBuilder::append_unsafe_put_raw(ciMethod* callee, BasicType t) {4273Values* args = state()->pop_arguments(callee->arg_size());4274null_check(args->at(0));4275Instruction* op = append(new UnsafePutRaw(t, args->at(1), args->at(2)));4276compilation()->set_has_unsafe_access(true);4277}427842794280void GraphBuilder::append_unsafe_CAS(ciMethod* callee) {4281ValueStack* state_before = copy_state_for_exception();4282ValueType* result_type = as_ValueType(callee->return_type());4283assert(result_type->is_int(), "int result");4284Values* args = state()->pop_arguments(callee->arg_size());42854286// Pop off some args to specially handle, then push back4287Value newval = args->pop();4288Value cmpval = args->pop();4289Value offset = args->pop();4290Value src = args->pop();4291Value unsafe_obj = args->pop();42924293// Separately handle the unsafe arg. It is not needed for code4294// generation, but must be null checked4295null_check(unsafe_obj);42964297#ifndef _LP644298offset = append(new Convert(Bytecodes::_l2i, offset, as_ValueType(T_INT)));4299#endif43004301args->push(src);4302args->push(offset);4303args->push(cmpval);4304args->push(newval);43054306// An unsafe CAS can alias with other field accesses, but we don't4307// know which ones so mark the state as no preserved. This will4308// cause CSE to invalidate memory across it.4309bool preserves_state = false;4310Intrinsic* result = new Intrinsic(result_type, callee->intrinsic_id(), args, false, state_before, preserves_state);4311append_split(result);4312push(result_type, result);4313compilation()->set_has_unsafe_access(true);4314}43154316void GraphBuilder::append_char_access(ciMethod* callee, bool is_store) {4317// This intrinsic accesses byte[] array as char[] array. Computing the offsets4318// correctly requires matched array shapes.4319assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),4320"sanity: byte[] and char[] bases agree");4321assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,4322"sanity: byte[] and char[] scales agree");43234324ValueStack* state_before = copy_state_indexed_access();4325compilation()->set_has_access_indexed(true);4326Values* args = state()->pop_arguments(callee->arg_size());4327Value array = args->at(0);4328Value index = args->at(1);4329if (is_store) {4330Value value = args->at(2);4331Instruction* store = append(new StoreIndexed(array, index, NULL, T_CHAR, value, state_before, false, true));4332store->set_flag(Instruction::NeedsRangeCheckFlag, false);4333_memory->store_value(value);4334} else {4335Instruction* load = append(new LoadIndexed(array, index, NULL, T_CHAR, state_before, true));4336load->set_flag(Instruction::NeedsRangeCheckFlag, false);4337push(load->type(), load);4338}4339}43404341void GraphBuilder::print_inlining(ciMethod* callee, const char* msg, bool success) {4342CompileLog* log = compilation()->log();4343if (log != NULL) {4344assert(msg != NULL, "inlining msg should not be null!");4345if (success) {4346log->inline_success(msg);4347} else {4348log->inline_fail(msg);4349}4350}4351EventCompilerInlining event;4352if (event.should_commit()) {4353CompilerEvent::InlineEvent::post(event, compilation()->env()->task()->compile_id(), method()->get_Method(), callee, success, msg, bci());4354}43554356CompileTask::print_inlining_ul(callee, scope()->level(), bci(), msg);43574358if (!compilation()->directive()->PrintInliningOption) {4359return;4360}4361CompileTask::print_inlining_tty(callee, scope()->level(), bci(), msg);4362if (success && CIPrintMethodCodes) {4363callee->print_codes();4364}4365}43664367void GraphBuilder::append_unsafe_get_and_set_obj(ciMethod* callee, bool is_add) {4368Values* args = state()->pop_arguments(callee->arg_size());4369BasicType t = callee->return_type()->basic_type();4370null_check(args->at(0));4371Instruction* offset = args->at(2);4372#ifndef _LP644373offset = append(new Convert(Bytecodes::_l2i, offset, as_ValueType(T_INT)));4374#endif4375Instruction* op = append(new UnsafeGetAndSetObject(t, args->at(1), offset, args->at(3), is_add));4376compilation()->set_has_unsafe_access(true);4377kill_all();4378push(op->type(), op);4379}43804381#ifndef PRODUCT4382void GraphBuilder::print_stats() {4383vmap()->print();4384}4385#endif // PRODUCT43864387void GraphBuilder::profile_call(ciMethod* callee, Value recv, ciKlass* known_holder, Values* obj_args, bool inlined) {4388assert(known_holder == NULL || (known_holder->is_instance_klass() &&4389(!known_holder->is_interface() ||4390((ciInstanceKlass*)known_holder)->has_nonstatic_concrete_methods())), "should be non-static concrete method");4391if (known_holder != NULL) {4392if (known_holder->exact_klass() == NULL) {4393known_holder = compilation()->cha_exact_type(known_holder);4394}4395}43964397append(new ProfileCall(method(), bci(), callee, recv, known_holder, obj_args, inlined));4398}43994400void GraphBuilder::profile_return_type(Value ret, ciMethod* callee, ciMethod* m, int invoke_bci) {4401assert((m == NULL) == (invoke_bci < 0), "invalid method and invalid bci together");4402if (m == NULL) {4403m = method();4404}4405if (invoke_bci < 0) {4406invoke_bci = bci();4407}4408ciMethodData* md = m->method_data_or_null();4409ciProfileData* data = md->bci_to_data(invoke_bci);4410if (data != NULL && (data->is_CallTypeData() || data->is_VirtualCallTypeData())) {4411bool has_return = data->is_CallTypeData() ? ((ciCallTypeData*)data)->has_return() : ((ciVirtualCallTypeData*)data)->has_return();4412if (has_return) {4413append(new ProfileReturnType(m , invoke_bci, callee, ret));4414}4415}4416}44174418void GraphBuilder::profile_invocation(ciMethod* callee, ValueStack* state) {4419append(new ProfileInvoke(callee, state));4420}442144224423