Path: blob/master/src/hotspot/share/c1/c1_Optimizer.cpp
40931 views
/*1* Copyright (c) 1999, 2020, 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_Canonicalizer.hpp"26#include "c1/c1_Optimizer.hpp"27#include "c1/c1_ValueMap.hpp"28#include "c1/c1_ValueSet.inline.hpp"29#include "c1/c1_ValueStack.hpp"30#include "memory/resourceArea.hpp"31#include "utilities/bitMap.inline.hpp"32#include "compiler/compileLog.hpp"3334typedef GrowableArray<ValueSet*> ValueSetList;3536Optimizer::Optimizer(IR* ir) {37assert(ir->is_valid(), "IR must be valid");38_ir = ir;39}4041class CE_Eliminator: public BlockClosure {42private:43IR* _hir;44int _cee_count; // the number of CEs successfully eliminated45int _ifop_count; // the number of IfOps successfully simplified46int _has_substitution;4748public:49CE_Eliminator(IR* hir) : _hir(hir), _cee_count(0), _ifop_count(0) {50_has_substitution = false;51_hir->iterate_preorder(this);52if (_has_substitution) {53// substituted some ifops/phis, so resolve the substitution54SubstitutionResolver sr(_hir);55}5657CompileLog* log = _hir->compilation()->log();58if (log != NULL)59log->set_context("optimize name='cee'");60}6162~CE_Eliminator() {63CompileLog* log = _hir->compilation()->log();64if (log != NULL)65log->clear_context(); // skip marker if nothing was printed66}6768int cee_count() const { return _cee_count; }69int ifop_count() const { return _ifop_count; }7071void adjust_exception_edges(BlockBegin* block, BlockBegin* sux) {72int e = sux->number_of_exception_handlers();73for (int i = 0; i < e; i++) {74BlockBegin* xhandler = sux->exception_handler_at(i);75block->add_exception_handler(xhandler);7677assert(xhandler->is_predecessor(sux), "missing predecessor");78if (sux->number_of_preds() == 0) {79// sux is disconnected from graph so disconnect from exception handlers80xhandler->remove_predecessor(sux);81}82if (!xhandler->is_predecessor(block)) {83xhandler->add_predecessor(block);84}85}86}8788virtual void block_do(BlockBegin* block);8990private:91Value make_ifop(Value x, Instruction::Condition cond, Value y, Value tval, Value fval);92};9394void CE_Eliminator::block_do(BlockBegin* block) {95// 1) find conditional expression96// check if block ends with an If97If* if_ = block->end()->as_If();98if (if_ == NULL) return;99100// check if If works on int or object types101// (we cannot handle If's working on long, float or doubles yet,102// since IfOp doesn't support them - these If's show up if cmp103// operations followed by If's are eliminated)104ValueType* if_type = if_->x()->type();105if (!if_type->is_int() && !if_type->is_object()) return;106107BlockBegin* t_block = if_->tsux();108BlockBegin* f_block = if_->fsux();109Instruction* t_cur = t_block->next();110Instruction* f_cur = f_block->next();111112// one Constant may be present between BlockBegin and BlockEnd113Value t_const = NULL;114Value f_const = NULL;115if (t_cur->as_Constant() != NULL && !t_cur->can_trap()) {116t_const = t_cur;117t_cur = t_cur->next();118}119if (f_cur->as_Constant() != NULL && !f_cur->can_trap()) {120f_const = f_cur;121f_cur = f_cur->next();122}123124// check if both branches end with a goto125Goto* t_goto = t_cur->as_Goto();126if (t_goto == NULL) return;127Goto* f_goto = f_cur->as_Goto();128if (f_goto == NULL) return;129130// check if both gotos merge into the same block131BlockBegin* sux = t_goto->default_sux();132if (sux != f_goto->default_sux()) return;133134// check if at least one word was pushed on sux_state135// inlining depths must match136ValueStack* if_state = if_->state();137ValueStack* sux_state = sux->state();138if (if_state->scope()->level() > sux_state->scope()->level()) {139while (sux_state->scope() != if_state->scope()) {140if_state = if_state->caller_state();141assert(if_state != NULL, "states do not match up");142}143} else if (if_state->scope()->level() < sux_state->scope()->level()) {144while (sux_state->scope() != if_state->scope()) {145sux_state = sux_state->caller_state();146assert(sux_state != NULL, "states do not match up");147}148}149150if (sux_state->stack_size() <= if_state->stack_size()) return;151152// check if phi function is present at end of successor stack and that153// only this phi was pushed on the stack154Value sux_phi = sux_state->stack_at(if_state->stack_size());155if (sux_phi == NULL || sux_phi->as_Phi() == NULL || sux_phi->as_Phi()->block() != sux) return;156if (sux_phi->type()->size() != sux_state->stack_size() - if_state->stack_size()) return;157158// get the values that were pushed in the true- and false-branch159Value t_value = t_goto->state()->stack_at(if_state->stack_size());160Value f_value = f_goto->state()->stack_at(if_state->stack_size());161162// backend does not support floats163assert(t_value->type()->base() == f_value->type()->base(), "incompatible types");164if (t_value->type()->is_float_kind()) return;165166// check that successor has no other phi functions but sux_phi167// this can happen when t_block or f_block contained additonal stores to local variables168// that are no longer represented by explicit instructions169for_each_phi_fun(sux, phi,170if (phi != sux_phi) return;171);172// true and false blocks can't have phis173for_each_phi_fun(t_block, phi, return; );174for_each_phi_fun(f_block, phi, return; );175176// Only replace safepoint gotos if state_before information is available (if is a safepoint)177bool is_safepoint = if_->is_safepoint();178if (!is_safepoint && (t_goto->is_safepoint() || f_goto->is_safepoint())) {179return;180}181182// 2) substitute conditional expression183// with an IfOp followed by a Goto184// cut if_ away and get node before185Instruction* cur_end = if_->prev();186187// append constants of true- and false-block if necessary188// clone constants because original block must not be destroyed189assert((t_value != f_const && f_value != t_const) || t_const == f_const, "mismatch");190if (t_value == t_const) {191t_value = new Constant(t_const->type());192NOT_PRODUCT(t_value->set_printable_bci(if_->printable_bci()));193cur_end = cur_end->set_next(t_value);194}195if (f_value == f_const) {196f_value = new Constant(f_const->type());197NOT_PRODUCT(f_value->set_printable_bci(if_->printable_bci()));198cur_end = cur_end->set_next(f_value);199}200201Value result = make_ifop(if_->x(), if_->cond(), if_->y(), t_value, f_value);202assert(result != NULL, "make_ifop must return a non-null instruction");203if (!result->is_linked() && result->can_be_linked()) {204NOT_PRODUCT(result->set_printable_bci(if_->printable_bci()));205cur_end = cur_end->set_next(result);206}207208// append Goto to successor209ValueStack* state_before = if_->state_before();210Goto* goto_ = new Goto(sux, state_before, is_safepoint);211212// prepare state for Goto213ValueStack* goto_state = if_state;214goto_state = goto_state->copy(ValueStack::StateAfter, goto_state->bci());215goto_state->push(result->type(), result);216assert(goto_state->is_same(sux_state), "states must match now");217goto_->set_state(goto_state);218219cur_end = cur_end->set_next(goto_, goto_state->bci());220221// Adjust control flow graph222BlockBegin::disconnect_edge(block, t_block);223BlockBegin::disconnect_edge(block, f_block);224if (t_block->number_of_preds() == 0) {225BlockBegin::disconnect_edge(t_block, sux);226}227adjust_exception_edges(block, t_block);228if (f_block->number_of_preds() == 0) {229BlockBegin::disconnect_edge(f_block, sux);230}231adjust_exception_edges(block, f_block);232233// update block end234block->set_end(goto_);235236// substitute the phi if possible237if (sux_phi->as_Phi()->operand_count() == 1) {238assert(sux_phi->as_Phi()->operand_at(0) == result, "screwed up phi");239sux_phi->set_subst(result);240_has_substitution = true;241}242243// 3) successfully eliminated a conditional expression244_cee_count++;245if (PrintCEE) {246tty->print_cr("%d. CEE in B%d (B%d B%d)", cee_count(), block->block_id(), t_block->block_id(), f_block->block_id());247tty->print_cr("%d. IfOp in B%d", ifop_count(), block->block_id());248}249250_hir->verify();251}252253Value CE_Eliminator::make_ifop(Value x, Instruction::Condition cond, Value y, Value tval, Value fval) {254if (!OptimizeIfOps) {255return new IfOp(x, cond, y, tval, fval);256}257258tval = tval->subst();259fval = fval->subst();260if (tval == fval) {261_ifop_count++;262return tval;263}264265x = x->subst();266y = y->subst();267268Constant* y_const = y->as_Constant();269if (y_const != NULL) {270IfOp* x_ifop = x->as_IfOp();271if (x_ifop != NULL) { // x is an ifop, y is a constant272Constant* x_tval_const = x_ifop->tval()->subst()->as_Constant();273Constant* x_fval_const = x_ifop->fval()->subst()->as_Constant();274275if (x_tval_const != NULL && x_fval_const != NULL) {276Instruction::Condition x_ifop_cond = x_ifop->cond();277278Constant::CompareResult t_compare_res = x_tval_const->compare(cond, y_const);279Constant::CompareResult f_compare_res = x_fval_const->compare(cond, y_const);280281// not_comparable here is a valid return in case we're comparing unloaded oop constants282if (t_compare_res != Constant::not_comparable && f_compare_res != Constant::not_comparable) {283Value new_tval = t_compare_res == Constant::cond_true ? tval : fval;284Value new_fval = f_compare_res == Constant::cond_true ? tval : fval;285286_ifop_count++;287if (new_tval == new_fval) {288return new_tval;289} else {290return new IfOp(x_ifop->x(), x_ifop_cond, x_ifop->y(), new_tval, new_fval);291}292}293}294} else {295Constant* x_const = x->as_Constant();296if (x_const != NULL) { // x and y are constants297Constant::CompareResult x_compare_res = x_const->compare(cond, y_const);298// not_comparable here is a valid return in case we're comparing unloaded oop constants299if (x_compare_res != Constant::not_comparable) {300_ifop_count++;301return x_compare_res == Constant::cond_true ? tval : fval;302}303}304}305}306return new IfOp(x, cond, y, tval, fval);307}308309void Optimizer::eliminate_conditional_expressions() {310// find conditional expressions & replace them with IfOps311CE_Eliminator ce(ir());312}313314class BlockMerger: public BlockClosure {315private:316IR* _hir;317int _merge_count; // the number of block pairs successfully merged318319public:320BlockMerger(IR* hir)321: _hir(hir)322, _merge_count(0)323{324_hir->iterate_preorder(this);325CompileLog* log = _hir->compilation()->log();326if (log != NULL)327log->set_context("optimize name='eliminate_blocks'");328}329330~BlockMerger() {331CompileLog* log = _hir->compilation()->log();332if (log != NULL)333log->clear_context(); // skip marker if nothing was printed334}335336bool try_merge(BlockBegin* block) {337BlockEnd* end = block->end();338if (end->as_Goto() != NULL) {339assert(end->number_of_sux() == 1, "end must have exactly one successor");340// Note: It would be sufficient to check for the number of successors (= 1)341// in order to decide if this block can be merged potentially. That342// would then also include switch statements w/ only a default case.343// However, in that case we would need to make sure the switch tag344// expression is executed if it can produce observable side effects.345// We should probably have the canonicalizer simplifying such switch346// statements and then we are sure we don't miss these merge opportunities347// here (was bug - gri 7/7/99).348BlockBegin* sux = end->default_sux();349if (sux->number_of_preds() == 1 && !sux->is_entry_block() && !end->is_safepoint()) {350// merge the two blocks351352#ifdef ASSERT353// verify that state at the end of block and at the beginning of sux are equal354// no phi functions must be present at beginning of sux355ValueStack* sux_state = sux->state();356ValueStack* end_state = end->state();357358assert(end_state->scope() == sux_state->scope(), "scopes must match");359assert(end_state->stack_size() == sux_state->stack_size(), "stack not equal");360assert(end_state->locals_size() == sux_state->locals_size(), "locals not equal");361362int index;363Value sux_value;364for_each_stack_value(sux_state, index, sux_value) {365assert(sux_value == end_state->stack_at(index), "stack not equal");366}367for_each_local_value(sux_state, index, sux_value) {368Phi* sux_phi = sux_value->as_Phi();369if (sux_phi != NULL && sux_phi->is_illegal()) continue;370assert(sux_value == end_state->local_at(index), "locals not equal");371}372assert(sux_state->caller_state() == end_state->caller_state(), "caller not equal");373#endif374375// find instruction before end & append first instruction of sux block376Instruction* prev = end->prev();377Instruction* next = sux->next();378assert(prev->as_BlockEnd() == NULL, "must not be a BlockEnd");379prev->set_next(next);380prev->fixup_block_pointers();381sux->disconnect_from_graph();382block->set_end(sux->end());383// add exception handlers of deleted block, if any384for (int k = 0; k < sux->number_of_exception_handlers(); k++) {385BlockBegin* xhandler = sux->exception_handler_at(k);386block->add_exception_handler(xhandler);387388// also substitute predecessor of exception handler389assert(xhandler->is_predecessor(sux), "missing predecessor");390xhandler->remove_predecessor(sux);391if (!xhandler->is_predecessor(block)) {392xhandler->add_predecessor(block);393}394}395396// debugging output397_merge_count++;398if (PrintBlockElimination) {399tty->print_cr("%d. merged B%d & B%d (stack size = %d)",400_merge_count, block->block_id(), sux->block_id(), sux->state()->stack_size());401}402403_hir->verify();404405If* if_ = block->end()->as_If();406if (if_) {407IfOp* ifop = if_->x()->as_IfOp();408Constant* con = if_->y()->as_Constant();409bool swapped = false;410if (!con || !ifop) {411ifop = if_->y()->as_IfOp();412con = if_->x()->as_Constant();413swapped = true;414}415if (con && ifop) {416Constant* tval = ifop->tval()->as_Constant();417Constant* fval = ifop->fval()->as_Constant();418if (tval && fval) {419// Find the instruction before if_, starting with ifop.420// When if_ and ifop are not in the same block, prev421// becomes NULL In such (rare) cases it is not422// profitable to perform the optimization.423Value prev = ifop;424while (prev != NULL && prev->next() != if_) {425prev = prev->next();426}427428if (prev != NULL) {429Instruction::Condition cond = if_->cond();430BlockBegin* tsux = if_->tsux();431BlockBegin* fsux = if_->fsux();432if (swapped) {433cond = Instruction::mirror(cond);434}435436BlockBegin* tblock = tval->compare(cond, con, tsux, fsux);437BlockBegin* fblock = fval->compare(cond, con, tsux, fsux);438if (tblock != fblock && !if_->is_safepoint()) {439If* newif = new If(ifop->x(), ifop->cond(), false, ifop->y(),440tblock, fblock, if_->state_before(), if_->is_safepoint());441newif->set_state(if_->state()->copy());442443assert(prev->next() == if_, "must be guaranteed by above search");444NOT_PRODUCT(newif->set_printable_bci(if_->printable_bci()));445prev->set_next(newif);446block->set_end(newif);447448_merge_count++;449if (PrintBlockElimination) {450tty->print_cr("%d. replaced If and IfOp at end of B%d with single If", _merge_count, block->block_id());451}452453_hir->verify();454}455}456}457}458}459460return true;461}462}463return false;464}465466virtual void block_do(BlockBegin* block) {467_hir->verify();468// repeat since the same block may merge again469while (try_merge(block)) {470_hir->verify();471}472}473};474475476void Optimizer::eliminate_blocks() {477// merge blocks if possible478BlockMerger bm(ir());479}480481482class NullCheckEliminator;483class NullCheckVisitor: public InstructionVisitor {484private:485NullCheckEliminator* _nce;486NullCheckEliminator* nce() { return _nce; }487488public:489NullCheckVisitor() {}490491void set_eliminator(NullCheckEliminator* nce) { _nce = nce; }492493void do_Phi (Phi* x);494void do_Local (Local* x);495void do_Constant (Constant* x);496void do_LoadField (LoadField* x);497void do_StoreField (StoreField* x);498void do_ArrayLength (ArrayLength* x);499void do_LoadIndexed (LoadIndexed* x);500void do_StoreIndexed (StoreIndexed* x);501void do_NegateOp (NegateOp* x);502void do_ArithmeticOp (ArithmeticOp* x);503void do_ShiftOp (ShiftOp* x);504void do_LogicOp (LogicOp* x);505void do_CompareOp (CompareOp* x);506void do_IfOp (IfOp* x);507void do_Convert (Convert* x);508void do_NullCheck (NullCheck* x);509void do_TypeCast (TypeCast* x);510void do_Invoke (Invoke* x);511void do_NewInstance (NewInstance* x);512void do_NewTypeArray (NewTypeArray* x);513void do_NewObjectArray (NewObjectArray* x);514void do_NewMultiArray (NewMultiArray* x);515void do_CheckCast (CheckCast* x);516void do_InstanceOf (InstanceOf* x);517void do_MonitorEnter (MonitorEnter* x);518void do_MonitorExit (MonitorExit* x);519void do_Intrinsic (Intrinsic* x);520void do_BlockBegin (BlockBegin* x);521void do_Goto (Goto* x);522void do_If (If* x);523void do_TableSwitch (TableSwitch* x);524void do_LookupSwitch (LookupSwitch* x);525void do_Return (Return* x);526void do_Throw (Throw* x);527void do_Base (Base* x);528void do_OsrEntry (OsrEntry* x);529void do_ExceptionObject(ExceptionObject* x);530void do_RoundFP (RoundFP* x);531void do_UnsafeGetRaw (UnsafeGetRaw* x);532void do_UnsafePutRaw (UnsafePutRaw* x);533void do_UnsafeGetObject(UnsafeGetObject* x);534void do_UnsafePutObject(UnsafePutObject* x);535void do_UnsafeGetAndSetObject(UnsafeGetAndSetObject* x);536void do_ProfileCall (ProfileCall* x);537void do_ProfileReturnType (ProfileReturnType* x);538void do_ProfileInvoke (ProfileInvoke* x);539void do_RuntimeCall (RuntimeCall* x);540void do_MemBar (MemBar* x);541void do_RangeCheckPredicate(RangeCheckPredicate* x);542#ifdef ASSERT543void do_Assert (Assert* x);544#endif545};546547548// Because of a static contained within (for the purpose of iteration549// over instructions), it is only valid to have one of these active at550// a time551class NullCheckEliminator: public ValueVisitor {552private:553Optimizer* _opt;554555ValueSet* _visitable_instructions; // Visit each instruction only once per basic block556BlockList* _work_list; // Basic blocks to visit557558bool visitable(Value x) {559assert(_visitable_instructions != NULL, "check");560return _visitable_instructions->contains(x);561}562void mark_visited(Value x) {563assert(_visitable_instructions != NULL, "check");564_visitable_instructions->remove(x);565}566void mark_visitable(Value x) {567assert(_visitable_instructions != NULL, "check");568_visitable_instructions->put(x);569}570void clear_visitable_state() {571assert(_visitable_instructions != NULL, "check");572_visitable_instructions->clear();573}574575ValueSet* _set; // current state, propagated to subsequent BlockBegins576ValueSetList _block_states; // BlockBegin null-check states for all processed blocks577NullCheckVisitor _visitor;578NullCheck* _last_explicit_null_check;579580bool set_contains(Value x) { assert(_set != NULL, "check"); return _set->contains(x); }581void set_put (Value x) { assert(_set != NULL, "check"); _set->put(x); }582void set_remove (Value x) { assert(_set != NULL, "check"); _set->remove(x); }583584BlockList* work_list() { return _work_list; }585586void iterate_all();587void iterate_one(BlockBegin* block);588589ValueSet* state() { return _set; }590void set_state_from (ValueSet* state) { _set->set_from(state); }591ValueSet* state_for (BlockBegin* block) { return _block_states.at(block->block_id()); }592void set_state_for (BlockBegin* block, ValueSet* stack) { _block_states.at_put(block->block_id(), stack); }593// Returns true if caused a change in the block's state.594bool merge_state_for(BlockBegin* block,595ValueSet* incoming_state);596597public:598// constructor599NullCheckEliminator(Optimizer* opt)600: _opt(opt)601, _work_list(new BlockList())602, _set(new ValueSet())603, _block_states(BlockBegin::number_of_blocks(), BlockBegin::number_of_blocks(), NULL)604, _last_explicit_null_check(NULL) {605_visitable_instructions = new ValueSet();606_visitor.set_eliminator(this);607CompileLog* log = _opt->ir()->compilation()->log();608if (log != NULL)609log->set_context("optimize name='null_check_elimination'");610}611612~NullCheckEliminator() {613CompileLog* log = _opt->ir()->compilation()->log();614if (log != NULL)615log->clear_context(); // skip marker if nothing was printed616}617618Optimizer* opt() { return _opt; }619IR* ir () { return opt()->ir(); }620621// Process a graph622void iterate(BlockBegin* root);623624void visit(Value* f);625626// In some situations (like NullCheck(x); getfield(x)) the debug627// information from the explicit NullCheck can be used to populate628// the getfield, even if the two instructions are in different629// scopes; this allows implicit null checks to be used but the630// correct exception information to be generated. We must clear the631// last-traversed NullCheck when we reach a potentially-exception-632// throwing instruction, as well as in some other cases.633void set_last_explicit_null_check(NullCheck* check) { _last_explicit_null_check = check; }634NullCheck* last_explicit_null_check() { return _last_explicit_null_check; }635Value last_explicit_null_check_obj() { return (_last_explicit_null_check636? _last_explicit_null_check->obj()637: NULL); }638NullCheck* consume_last_explicit_null_check() {639_last_explicit_null_check->unpin(Instruction::PinExplicitNullCheck);640_last_explicit_null_check->set_can_trap(false);641return _last_explicit_null_check;642}643void clear_last_explicit_null_check() { _last_explicit_null_check = NULL; }644645// Handlers for relevant instructions646// (separated out from NullCheckVisitor for clarity)647648// The basic contract is that these must leave the instruction in649// the desired state; must not assume anything about the state of650// the instruction. We make multiple passes over some basic blocks651// and the last pass is the only one whose result is valid.652void handle_AccessField (AccessField* x);653void handle_ArrayLength (ArrayLength* x);654void handle_LoadIndexed (LoadIndexed* x);655void handle_StoreIndexed (StoreIndexed* x);656void handle_NullCheck (NullCheck* x);657void handle_Invoke (Invoke* x);658void handle_NewInstance (NewInstance* x);659void handle_NewArray (NewArray* x);660void handle_AccessMonitor (AccessMonitor* x);661void handle_Intrinsic (Intrinsic* x);662void handle_ExceptionObject (ExceptionObject* x);663void handle_Phi (Phi* x);664void handle_ProfileCall (ProfileCall* x);665void handle_ProfileReturnType (ProfileReturnType* x);666};667668669// NEEDS_CLEANUP670// There may be other instructions which need to clear the last671// explicit null check. Anything across which we can not hoist the672// debug information for a NullCheck instruction must clear it. It673// might be safer to pattern match "NullCheck ; {AccessField,674// ArrayLength, LoadIndexed}" but it is more easily structured this way.675// Should test to see performance hit of clearing it for all handlers676// with empty bodies below. If it is negligible then we should leave677// that in for safety, otherwise should think more about it.678void NullCheckVisitor::do_Phi (Phi* x) { nce()->handle_Phi(x); }679void NullCheckVisitor::do_Local (Local* x) {}680void NullCheckVisitor::do_Constant (Constant* x) { /* FIXME: handle object constants */ }681void NullCheckVisitor::do_LoadField (LoadField* x) { nce()->handle_AccessField(x); }682void NullCheckVisitor::do_StoreField (StoreField* x) { nce()->handle_AccessField(x); }683void NullCheckVisitor::do_ArrayLength (ArrayLength* x) { nce()->handle_ArrayLength(x); }684void NullCheckVisitor::do_LoadIndexed (LoadIndexed* x) { nce()->handle_LoadIndexed(x); }685void NullCheckVisitor::do_StoreIndexed (StoreIndexed* x) { nce()->handle_StoreIndexed(x); }686void NullCheckVisitor::do_NegateOp (NegateOp* x) {}687void NullCheckVisitor::do_ArithmeticOp (ArithmeticOp* x) { if (x->can_trap()) nce()->clear_last_explicit_null_check(); }688void NullCheckVisitor::do_ShiftOp (ShiftOp* x) {}689void NullCheckVisitor::do_LogicOp (LogicOp* x) {}690void NullCheckVisitor::do_CompareOp (CompareOp* x) {}691void NullCheckVisitor::do_IfOp (IfOp* x) {}692void NullCheckVisitor::do_Convert (Convert* x) {}693void NullCheckVisitor::do_NullCheck (NullCheck* x) { nce()->handle_NullCheck(x); }694void NullCheckVisitor::do_TypeCast (TypeCast* x) {}695void NullCheckVisitor::do_Invoke (Invoke* x) { nce()->handle_Invoke(x); }696void NullCheckVisitor::do_NewInstance (NewInstance* x) { nce()->handle_NewInstance(x); }697void NullCheckVisitor::do_NewTypeArray (NewTypeArray* x) { nce()->handle_NewArray(x); }698void NullCheckVisitor::do_NewObjectArray (NewObjectArray* x) { nce()->handle_NewArray(x); }699void NullCheckVisitor::do_NewMultiArray (NewMultiArray* x) { nce()->handle_NewArray(x); }700void NullCheckVisitor::do_CheckCast (CheckCast* x) { nce()->clear_last_explicit_null_check(); }701void NullCheckVisitor::do_InstanceOf (InstanceOf* x) {}702void NullCheckVisitor::do_MonitorEnter (MonitorEnter* x) { nce()->handle_AccessMonitor(x); }703void NullCheckVisitor::do_MonitorExit (MonitorExit* x) { nce()->handle_AccessMonitor(x); }704void NullCheckVisitor::do_Intrinsic (Intrinsic* x) { nce()->handle_Intrinsic(x); }705void NullCheckVisitor::do_BlockBegin (BlockBegin* x) {}706void NullCheckVisitor::do_Goto (Goto* x) {}707void NullCheckVisitor::do_If (If* x) {}708void NullCheckVisitor::do_TableSwitch (TableSwitch* x) {}709void NullCheckVisitor::do_LookupSwitch (LookupSwitch* x) {}710void NullCheckVisitor::do_Return (Return* x) {}711void NullCheckVisitor::do_Throw (Throw* x) { nce()->clear_last_explicit_null_check(); }712void NullCheckVisitor::do_Base (Base* x) {}713void NullCheckVisitor::do_OsrEntry (OsrEntry* x) {}714void NullCheckVisitor::do_ExceptionObject(ExceptionObject* x) { nce()->handle_ExceptionObject(x); }715void NullCheckVisitor::do_RoundFP (RoundFP* x) {}716void NullCheckVisitor::do_UnsafeGetRaw (UnsafeGetRaw* x) {}717void NullCheckVisitor::do_UnsafePutRaw (UnsafePutRaw* x) {}718void NullCheckVisitor::do_UnsafeGetObject(UnsafeGetObject* x) {}719void NullCheckVisitor::do_UnsafePutObject(UnsafePutObject* x) {}720void NullCheckVisitor::do_UnsafeGetAndSetObject(UnsafeGetAndSetObject* x) {}721void NullCheckVisitor::do_ProfileCall (ProfileCall* x) { nce()->clear_last_explicit_null_check();722nce()->handle_ProfileCall(x); }723void NullCheckVisitor::do_ProfileReturnType (ProfileReturnType* x) { nce()->handle_ProfileReturnType(x); }724void NullCheckVisitor::do_ProfileInvoke (ProfileInvoke* x) {}725void NullCheckVisitor::do_RuntimeCall (RuntimeCall* x) {}726void NullCheckVisitor::do_MemBar (MemBar* x) {}727void NullCheckVisitor::do_RangeCheckPredicate(RangeCheckPredicate* x) {}728#ifdef ASSERT729void NullCheckVisitor::do_Assert (Assert* x) {}730#endif731732void NullCheckEliminator::visit(Value* p) {733assert(*p != NULL, "should not find NULL instructions");734if (visitable(*p)) {735mark_visited(*p);736(*p)->visit(&_visitor);737}738}739740bool NullCheckEliminator::merge_state_for(BlockBegin* block, ValueSet* incoming_state) {741ValueSet* state = state_for(block);742if (state == NULL) {743state = incoming_state->copy();744set_state_for(block, state);745return true;746} else {747bool changed = state->set_intersect(incoming_state);748if (PrintNullCheckElimination && changed) {749tty->print_cr("Block %d's null check state changed", block->block_id());750}751return changed;752}753}754755756void NullCheckEliminator::iterate_all() {757while (work_list()->length() > 0) {758iterate_one(work_list()->pop());759}760}761762763void NullCheckEliminator::iterate_one(BlockBegin* block) {764clear_visitable_state();765// clear out an old explicit null checks766set_last_explicit_null_check(NULL);767768if (PrintNullCheckElimination) {769tty->print_cr(" ...iterating block %d in null check elimination for %s::%s%s",770block->block_id(),771ir()->method()->holder()->name()->as_utf8(),772ir()->method()->name()->as_utf8(),773ir()->method()->signature()->as_symbol()->as_utf8());774}775776// Create new state if none present (only happens at root)777if (state_for(block) == NULL) {778ValueSet* tmp_state = new ValueSet();779set_state_for(block, tmp_state);780// Initial state is that local 0 (receiver) is non-null for781// non-static methods782ValueStack* stack = block->state();783IRScope* scope = stack->scope();784ciMethod* method = scope->method();785if (!method->is_static()) {786Local* local0 = stack->local_at(0)->as_Local();787assert(local0 != NULL, "must be");788assert(local0->type() == objectType, "invalid type of receiver");789790if (local0 != NULL) {791// Local 0 is used in this scope792tmp_state->put(local0);793if (PrintNullCheckElimination) {794tty->print_cr("Local 0 (value %d) proven non-null upon entry", local0->id());795}796}797}798}799800// Must copy block's state to avoid mutating it during iteration801// through the block -- otherwise "not-null" states can accidentally802// propagate "up" through the block during processing of backward803// branches and algorithm is incorrect (and does not converge)804set_state_from(state_for(block));805806// allow visiting of Phis belonging to this block807for_each_phi_fun(block, phi,808mark_visitable(phi);809);810811BlockEnd* e = block->end();812assert(e != NULL, "incomplete graph");813int i;814815// Propagate the state before this block into the exception816// handlers. They aren't true successors since we aren't guaranteed817// to execute the whole block before executing them. Also putting818// them on first seems to help reduce the amount of iteration to819// reach a fixed point.820for (i = 0; i < block->number_of_exception_handlers(); i++) {821BlockBegin* next = block->exception_handler_at(i);822if (merge_state_for(next, state())) {823if (!work_list()->contains(next)) {824work_list()->push(next);825}826}827}828829// Iterate through block, updating state.830for (Instruction* instr = block; instr != NULL; instr = instr->next()) {831// Mark instructions in this block as visitable as they are seen832// in the instruction list. This keeps the iteration from833// visiting instructions which are references in other blocks or834// visiting instructions more than once.835mark_visitable(instr);836if (instr->is_pinned() || instr->can_trap() || (instr->as_NullCheck() != NULL)) {837mark_visited(instr);838instr->input_values_do(this);839instr->visit(&_visitor);840}841}842843// Propagate state to successors if necessary844for (i = 0; i < e->number_of_sux(); i++) {845BlockBegin* next = e->sux_at(i);846if (merge_state_for(next, state())) {847if (!work_list()->contains(next)) {848work_list()->push(next);849}850}851}852}853854855void NullCheckEliminator::iterate(BlockBegin* block) {856work_list()->push(block);857iterate_all();858}859860void NullCheckEliminator::handle_AccessField(AccessField* x) {861if (x->is_static()) {862if (x->as_LoadField() != NULL) {863// If the field is a non-null static final object field (as is864// often the case for sun.misc.Unsafe), put this LoadField into865// the non-null map866ciField* field = x->field();867if (field->is_constant()) {868ciConstant field_val = field->constant_value();869BasicType field_type = field_val.basic_type();870if (is_reference_type(field_type)) {871ciObject* obj_val = field_val.as_object();872if (!obj_val->is_null_object()) {873if (PrintNullCheckElimination) {874tty->print_cr("AccessField %d proven non-null by static final non-null oop check",875x->id());876}877set_put(x);878}879}880}881}882// Be conservative883clear_last_explicit_null_check();884return;885}886887Value obj = x->obj();888if (set_contains(obj)) {889// Value is non-null => update AccessField890if (last_explicit_null_check_obj() == obj && !x->needs_patching()) {891x->set_explicit_null_check(consume_last_explicit_null_check());892x->set_needs_null_check(true);893if (PrintNullCheckElimination) {894tty->print_cr("Folded NullCheck %d into AccessField %d's null check for value %d",895x->explicit_null_check()->id(), x->id(), obj->id());896}897} else {898x->set_explicit_null_check(NULL);899x->set_needs_null_check(false);900if (PrintNullCheckElimination) {901tty->print_cr("Eliminated AccessField %d's null check for value %d", x->id(), obj->id());902}903}904} else {905set_put(obj);906if (PrintNullCheckElimination) {907tty->print_cr("AccessField %d of value %d proves value to be non-null", x->id(), obj->id());908}909// Ensure previous passes do not cause wrong state910x->set_needs_null_check(true);911x->set_explicit_null_check(NULL);912}913clear_last_explicit_null_check();914}915916917void NullCheckEliminator::handle_ArrayLength(ArrayLength* x) {918Value array = x->array();919if (set_contains(array)) {920// Value is non-null => update AccessArray921if (last_explicit_null_check_obj() == array) {922x->set_explicit_null_check(consume_last_explicit_null_check());923x->set_needs_null_check(true);924if (PrintNullCheckElimination) {925tty->print_cr("Folded NullCheck %d into ArrayLength %d's null check for value %d",926x->explicit_null_check()->id(), x->id(), array->id());927}928} else {929x->set_explicit_null_check(NULL);930x->set_needs_null_check(false);931if (PrintNullCheckElimination) {932tty->print_cr("Eliminated ArrayLength %d's null check for value %d", x->id(), array->id());933}934}935} else {936set_put(array);937if (PrintNullCheckElimination) {938tty->print_cr("ArrayLength %d of value %d proves value to be non-null", x->id(), array->id());939}940// Ensure previous passes do not cause wrong state941x->set_needs_null_check(true);942x->set_explicit_null_check(NULL);943}944clear_last_explicit_null_check();945}946947948void NullCheckEliminator::handle_LoadIndexed(LoadIndexed* x) {949Value array = x->array();950if (set_contains(array)) {951// Value is non-null => update AccessArray952if (last_explicit_null_check_obj() == array) {953x->set_explicit_null_check(consume_last_explicit_null_check());954x->set_needs_null_check(true);955if (PrintNullCheckElimination) {956tty->print_cr("Folded NullCheck %d into LoadIndexed %d's null check for value %d",957x->explicit_null_check()->id(), x->id(), array->id());958}959} else {960x->set_explicit_null_check(NULL);961x->set_needs_null_check(false);962if (PrintNullCheckElimination) {963tty->print_cr("Eliminated LoadIndexed %d's null check for value %d", x->id(), array->id());964}965}966} else {967set_put(array);968if (PrintNullCheckElimination) {969tty->print_cr("LoadIndexed %d of value %d proves value to be non-null", x->id(), array->id());970}971// Ensure previous passes do not cause wrong state972x->set_needs_null_check(true);973x->set_explicit_null_check(NULL);974}975clear_last_explicit_null_check();976}977978979void NullCheckEliminator::handle_StoreIndexed(StoreIndexed* x) {980Value array = x->array();981if (set_contains(array)) {982// Value is non-null => update AccessArray983if (PrintNullCheckElimination) {984tty->print_cr("Eliminated StoreIndexed %d's null check for value %d", x->id(), array->id());985}986x->set_needs_null_check(false);987} else {988set_put(array);989if (PrintNullCheckElimination) {990tty->print_cr("StoreIndexed %d of value %d proves value to be non-null", x->id(), array->id());991}992// Ensure previous passes do not cause wrong state993x->set_needs_null_check(true);994}995clear_last_explicit_null_check();996}997998999void NullCheckEliminator::handle_NullCheck(NullCheck* x) {1000Value obj = x->obj();1001if (set_contains(obj)) {1002// Already proven to be non-null => this NullCheck is useless1003if (PrintNullCheckElimination) {1004tty->print_cr("Eliminated NullCheck %d for value %d", x->id(), obj->id());1005}1006// Don't unpin since that may shrink obj's live range and make it unavailable for debug info.1007// The code generator won't emit LIR for a NullCheck that cannot trap.1008x->set_can_trap(false);1009} else {1010// May be null => add to map and set last explicit NullCheck1011x->set_can_trap(true);1012// make sure it's pinned if it can trap1013x->pin(Instruction::PinExplicitNullCheck);1014set_put(obj);1015set_last_explicit_null_check(x);1016if (PrintNullCheckElimination) {1017tty->print_cr("NullCheck %d of value %d proves value to be non-null", x->id(), obj->id());1018}1019}1020}102110221023void NullCheckEliminator::handle_Invoke(Invoke* x) {1024if (!x->has_receiver()) {1025// Be conservative1026clear_last_explicit_null_check();1027return;1028}10291030Value recv = x->receiver();1031if (!set_contains(recv)) {1032set_put(recv);1033if (PrintNullCheckElimination) {1034tty->print_cr("Invoke %d of value %d proves value to be non-null", x->id(), recv->id());1035}1036}1037clear_last_explicit_null_check();1038}103910401041void NullCheckEliminator::handle_NewInstance(NewInstance* x) {1042set_put(x);1043if (PrintNullCheckElimination) {1044tty->print_cr("NewInstance %d is non-null", x->id());1045}1046}104710481049void NullCheckEliminator::handle_NewArray(NewArray* x) {1050set_put(x);1051if (PrintNullCheckElimination) {1052tty->print_cr("NewArray %d is non-null", x->id());1053}1054}105510561057void NullCheckEliminator::handle_ExceptionObject(ExceptionObject* x) {1058set_put(x);1059if (PrintNullCheckElimination) {1060tty->print_cr("ExceptionObject %d is non-null", x->id());1061}1062}106310641065void NullCheckEliminator::handle_AccessMonitor(AccessMonitor* x) {1066Value obj = x->obj();1067if (set_contains(obj)) {1068// Value is non-null => update AccessMonitor1069if (PrintNullCheckElimination) {1070tty->print_cr("Eliminated AccessMonitor %d's null check for value %d", x->id(), obj->id());1071}1072x->set_needs_null_check(false);1073} else {1074set_put(obj);1075if (PrintNullCheckElimination) {1076tty->print_cr("AccessMonitor %d of value %d proves value to be non-null", x->id(), obj->id());1077}1078// Ensure previous passes do not cause wrong state1079x->set_needs_null_check(true);1080}1081clear_last_explicit_null_check();1082}108310841085void NullCheckEliminator::handle_Intrinsic(Intrinsic* x) {1086if (!x->has_receiver()) {1087if (x->id() == vmIntrinsics::_arraycopy) {1088for (int i = 0; i < x->number_of_arguments(); i++) {1089x->set_arg_needs_null_check(i, !set_contains(x->argument_at(i)));1090}1091}10921093// Be conservative1094clear_last_explicit_null_check();1095return;1096}10971098Value recv = x->receiver();1099if (set_contains(recv)) {1100// Value is non-null => update Intrinsic1101if (PrintNullCheckElimination) {1102tty->print_cr("Eliminated Intrinsic %d's null check for value %d", vmIntrinsics::as_int(x->id()), recv->id());1103}1104x->set_needs_null_check(false);1105} else {1106set_put(recv);1107if (PrintNullCheckElimination) {1108tty->print_cr("Intrinsic %d of value %d proves value to be non-null", vmIntrinsics::as_int(x->id()), recv->id());1109}1110// Ensure previous passes do not cause wrong state1111x->set_needs_null_check(true);1112}1113clear_last_explicit_null_check();1114}111511161117void NullCheckEliminator::handle_Phi(Phi* x) {1118int i;1119bool all_non_null = true;1120if (x->is_illegal()) {1121all_non_null = false;1122} else {1123for (i = 0; i < x->operand_count(); i++) {1124Value input = x->operand_at(i);1125if (!set_contains(input)) {1126all_non_null = false;1127}1128}1129}11301131if (all_non_null) {1132// Value is non-null => update Phi1133if (PrintNullCheckElimination) {1134tty->print_cr("Eliminated Phi %d's null check for phifun because all inputs are non-null", x->id());1135}1136x->set_needs_null_check(false);1137} else if (set_contains(x)) {1138set_remove(x);1139}1140}11411142void NullCheckEliminator::handle_ProfileCall(ProfileCall* x) {1143for (int i = 0; i < x->nb_profiled_args(); i++) {1144x->set_arg_needs_null_check(i, !set_contains(x->profiled_arg_at(i)));1145}1146}11471148void NullCheckEliminator::handle_ProfileReturnType(ProfileReturnType* x) {1149x->set_needs_null_check(!set_contains(x->ret()));1150}11511152void Optimizer::eliminate_null_checks() {1153ResourceMark rm;11541155NullCheckEliminator nce(this);11561157if (PrintNullCheckElimination) {1158tty->print_cr("Starting null check elimination for method %s::%s%s",1159ir()->method()->holder()->name()->as_utf8(),1160ir()->method()->name()->as_utf8(),1161ir()->method()->signature()->as_symbol()->as_utf8());1162}11631164// Apply to graph1165nce.iterate(ir()->start());11661167// walk over the graph looking for exception1168// handlers and iterate over them as well1169int nblocks = BlockBegin::number_of_blocks();1170BlockList blocks(nblocks);1171boolArray visited_block(nblocks, nblocks, false);11721173blocks.push(ir()->start());1174visited_block.at_put(ir()->start()->block_id(), true);1175for (int i = 0; i < blocks.length(); i++) {1176BlockBegin* b = blocks.at(i);1177// exception handlers need to be treated as additional roots1178for (int e = b->number_of_exception_handlers(); e-- > 0; ) {1179BlockBegin* excp = b->exception_handler_at(e);1180int id = excp->block_id();1181if (!visited_block.at(id)) {1182blocks.push(excp);1183visited_block.at_put(id, true);1184nce.iterate(excp);1185}1186}1187// traverse successors1188BlockEnd *end = b->end();1189for (int s = end->number_of_sux(); s-- > 0; ) {1190BlockBegin* next = end->sux_at(s);1191int id = next->block_id();1192if (!visited_block.at(id)) {1193blocks.push(next);1194visited_block.at_put(id, true);1195}1196}1197}119811991200if (PrintNullCheckElimination) {1201tty->print_cr("Done with null check elimination for method %s::%s%s",1202ir()->method()->holder()->name()->as_utf8(),1203ir()->method()->name()->as_utf8(),1204ir()->method()->signature()->as_symbol()->as_utf8());1205}1206}120712081209