1 /*
   2  * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "c1/c1_Canonicalizer.hpp"
  27 #include "c1/c1_Optimizer.hpp"
  28 #include "c1/c1_ValueMap.hpp"
  29 #include "c1/c1_ValueSet.inline.hpp"
  30 #include "c1/c1_ValueStack.hpp"
  31 #include "memory/resourceArea.hpp"
  32 #include "utilities/bitMap.inline.hpp"
  33 #include "compiler/compileLog.hpp"
  34 
  35 typedef GrowableArray<ValueSet*> ValueSetList;
  36 
  37 Optimizer::Optimizer(IR* ir) {
  38   assert(ir->is_valid(), "IR must be valid");
  39   _ir = ir;
  40 }
  41 
  42 class CE_Eliminator: public BlockClosure {
  43  private:
  44   IR* _hir;
  45   int _cee_count;                                // the number of CEs successfully eliminated
  46   int _ifop_count;                               // the number of IfOps successfully simplified
  47   int _has_substitution;
  48 
  49  public:
  50   CE_Eliminator(IR* hir) : _hir(hir), _cee_count(0), _ifop_count(0) {
  51     _has_substitution = false;
  52     _hir->iterate_preorder(this);
  53     if (_has_substitution) {
  54       // substituted some ifops/phis, so resolve the substitution
  55       SubstitutionResolver sr(_hir);
  56     }
  57 
  58     CompileLog* log = _hir->compilation()->log();
  59     if (log != NULL)
  60       log->set_context("optimize name='cee'");
  61   }
  62 
  63   ~CE_Eliminator() {
  64     CompileLog* log = _hir->compilation()->log();
  65     if (log != NULL)
  66       log->clear_context(); // skip marker if nothing was printed
  67   }
  68 
  69   int cee_count() const                          { return _cee_count; }
  70   int ifop_count() const                         { return _ifop_count; }
  71 
  72   void adjust_exception_edges(BlockBegin* block, BlockBegin* sux) {
  73     int e = sux->number_of_exception_handlers();
  74     for (int i = 0; i < e; i++) {
  75       BlockBegin* xhandler = sux->exception_handler_at(i);
  76       block->add_exception_handler(xhandler);
  77 
  78       assert(xhandler->is_predecessor(sux), "missing predecessor");
  79       if (sux->number_of_preds() == 0) {
  80         // sux is disconnected from graph so disconnect from exception handlers
  81         xhandler->remove_predecessor(sux);
  82       }
  83       if (!xhandler->is_predecessor(block)) {
  84         xhandler->add_predecessor(block);
  85       }
  86     }
  87   }
  88 
  89   virtual void block_do(BlockBegin* block);
  90 
  91  private:
  92   Value make_ifop(Value x, Instruction::Condition cond, Value y, Value tval, Value fval,
  93                   ValueStack* state_before, bool substitutability_check);
  94 };
  95 
  96 void CE_Eliminator::block_do(BlockBegin* block) {
  97   // 1) find conditional expression
  98   // check if block ends with an If
  99   If* if_ = block->end()->as_If();
 100   if (if_ == NULL) return;
 101 
 102   // check if If works on int or object types
 103   // (we cannot handle If's working on long, float or doubles yet,
 104   // since IfOp doesn't support them - these If's show up if cmp
 105   // operations followed by If's are eliminated)
 106   ValueType* if_type = if_->x()->type();
 107   if (!if_type->is_int() && !if_type->is_object()) return;
 108 
 109   BlockBegin* t_block = if_->tsux();
 110   BlockBegin* f_block = if_->fsux();
 111   Instruction* t_cur = t_block->next();
 112   Instruction* f_cur = f_block->next();
 113 
 114   // one Constant may be present between BlockBegin and BlockEnd
 115   Value t_const = NULL;
 116   Value f_const = NULL;
 117   if (t_cur->as_Constant() != NULL && !t_cur->can_trap()) {
 118     t_const = t_cur;
 119     t_cur = t_cur->next();
 120   }
 121   if (f_cur->as_Constant() != NULL && !f_cur->can_trap()) {
 122     f_const = f_cur;
 123     f_cur = f_cur->next();
 124   }
 125 
 126   // check if both branches end with a goto
 127   Goto* t_goto = t_cur->as_Goto();
 128   if (t_goto == NULL) return;
 129   Goto* f_goto = f_cur->as_Goto();
 130   if (f_goto == NULL) return;
 131 
 132   // check if both gotos merge into the same block
 133   BlockBegin* sux = t_goto->default_sux();
 134   if (sux != f_goto->default_sux()) return;
 135 
 136   // check if at least one word was pushed on sux_state
 137   // inlining depths must match
 138   ValueStack* if_state = if_->state();
 139   ValueStack* sux_state = sux->state();
 140   if (if_state->scope()->level() > sux_state->scope()->level()) {
 141     while (sux_state->scope() != if_state->scope()) {
 142       if_state = if_state->caller_state();
 143       assert(if_state != NULL, "states do not match up");
 144     }
 145   } else if (if_state->scope()->level() < sux_state->scope()->level()) {
 146     while (sux_state->scope() != if_state->scope()) {
 147       sux_state = sux_state->caller_state();
 148       assert(sux_state != NULL, "states do not match up");
 149     }
 150   }
 151 
 152   if (sux_state->stack_size() <= if_state->stack_size()) return;
 153 
 154   // check if phi function is present at end of successor stack and that
 155   // only this phi was pushed on the stack
 156   Value sux_phi = sux_state->stack_at(if_state->stack_size());
 157   if (sux_phi == NULL || sux_phi->as_Phi() == NULL || sux_phi->as_Phi()->block() != sux) return;
 158   if (sux_phi->type()->size() != sux_state->stack_size() - if_state->stack_size()) return;
 159 
 160   // get the values that were pushed in the true- and false-branch
 161   Value t_value = t_goto->state()->stack_at(if_state->stack_size());
 162   Value f_value = f_goto->state()->stack_at(if_state->stack_size());
 163 
 164   // backend does not support floats
 165   assert(t_value->type()->base() == f_value->type()->base(), "incompatible types");
 166   if (t_value->type()->is_float_kind()) return;
 167 
 168   // check that successor has no other phi functions but sux_phi
 169   // this can happen when t_block or f_block contained additonal stores to local variables
 170   // that are no longer represented by explicit instructions
 171   for_each_phi_fun(sux, phi,
 172                    if (phi != sux_phi) return;
 173                    );
 174   // true and false blocks can't have phis
 175   for_each_phi_fun(t_block, phi, return; );
 176   for_each_phi_fun(f_block, phi, return; );
 177 
 178   // Only replace safepoint gotos if state_before information is available (if is a safepoint)
 179   bool is_safepoint = if_->is_safepoint();
 180   if (!is_safepoint && (t_goto->is_safepoint() || f_goto->is_safepoint())) {
 181     return;
 182   }
 183 
 184   // 2) substitute conditional expression
 185   //    with an IfOp followed by a Goto
 186   // cut if_ away and get node before
 187   Instruction* cur_end = if_->prev();
 188 
 189   // append constants of true- and false-block if necessary
 190   // clone constants because original block must not be destroyed
 191   assert((t_value != f_const && f_value != t_const) || t_const == f_const, "mismatch");
 192   if (t_value == t_const) {
 193     t_value = new Constant(t_const->type());
 194     NOT_PRODUCT(t_value->set_printable_bci(if_->printable_bci()));
 195     cur_end = cur_end->set_next(t_value);
 196   }
 197   if (f_value == f_const) {
 198     f_value = new Constant(f_const->type());
 199     NOT_PRODUCT(f_value->set_printable_bci(if_->printable_bci()));
 200     cur_end = cur_end->set_next(f_value);
 201   }
 202 
 203   Value result = make_ifop(if_->x(), if_->cond(), if_->y(), t_value, f_value,
 204                            if_->state_before(), if_->substitutability_check());
 205   assert(result != NULL, "make_ifop must return a non-null instruction");
 206   if (!result->is_linked() && result->can_be_linked()) {
 207     NOT_PRODUCT(result->set_printable_bci(if_->printable_bci()));
 208     cur_end = cur_end->set_next(result);
 209   }
 210 
 211   // append Goto to successor
 212   ValueStack* state_before = if_->state_before();
 213   Goto* goto_ = new Goto(sux, state_before, is_safepoint);
 214 
 215   // prepare state for Goto
 216   ValueStack* goto_state = if_state;
 217   goto_state = goto_state->copy(ValueStack::StateAfter, goto_state->bci());
 218   goto_state->push(result->type(), result);
 219   assert(goto_state->is_same(sux_state), "states must match now");
 220   goto_->set_state(goto_state);
 221 
 222   cur_end = cur_end->set_next(goto_, goto_state->bci());
 223 
 224   // Adjust control flow graph
 225   BlockBegin::disconnect_edge(block, t_block);
 226   BlockBegin::disconnect_edge(block, f_block);
 227   if (t_block->number_of_preds() == 0) {
 228     BlockBegin::disconnect_edge(t_block, sux);
 229   }
 230   adjust_exception_edges(block, t_block);
 231   if (f_block->number_of_preds() == 0) {
 232     BlockBegin::disconnect_edge(f_block, sux);
 233   }
 234   adjust_exception_edges(block, f_block);
 235 
 236   // update block end
 237   block->set_end(goto_);
 238 
 239   // substitute the phi if possible
 240   if (sux_phi->as_Phi()->operand_count() == 1) {
 241     assert(sux_phi->as_Phi()->operand_at(0) == result, "screwed up phi");
 242     sux_phi->set_subst(result);
 243     _has_substitution = true;
 244   }
 245 
 246   // 3) successfully eliminated a conditional expression
 247   _cee_count++;
 248   if (PrintCEE) {
 249     tty->print_cr("%d. CEE in B%d (B%d B%d)", cee_count(), block->block_id(), t_block->block_id(), f_block->block_id());
 250     tty->print_cr("%d. IfOp in B%d", ifop_count(), block->block_id());
 251   }
 252 
 253   _hir->verify();
 254 }
 255 
 256 Value CE_Eliminator::make_ifop(Value x, Instruction::Condition cond, Value y, Value tval, Value fval,
 257                                ValueStack* state_before, bool substitutability_check) {
 258   if (!OptimizeIfOps) {
 259     return new IfOp(x, cond, y, tval, fval, state_before, substitutability_check);
 260   }
 261 
 262   tval = tval->subst();
 263   fval = fval->subst();
 264   if (tval == fval) {
 265     _ifop_count++;
 266     return tval;
 267   }
 268 
 269   x = x->subst();
 270   y = y->subst();
 271 
 272   Constant* y_const = y->as_Constant();
 273   if (y_const != NULL) {
 274     IfOp* x_ifop = x->as_IfOp();
 275     if (x_ifop != NULL) {                 // x is an ifop, y is a constant
 276       Constant* x_tval_const = x_ifop->tval()->subst()->as_Constant();
 277       Constant* x_fval_const = x_ifop->fval()->subst()->as_Constant();
 278 
 279       if (x_tval_const != NULL && x_fval_const != NULL) {
 280         Instruction::Condition x_ifop_cond = x_ifop->cond();
 281 
 282         Constant::CompareResult t_compare_res = x_tval_const->compare(cond, y_const);
 283         Constant::CompareResult f_compare_res = x_fval_const->compare(cond, y_const);
 284 
 285         // not_comparable here is a valid return in case we're comparing unloaded oop constants
 286         if (t_compare_res != Constant::not_comparable && f_compare_res != Constant::not_comparable) {
 287           Value new_tval = t_compare_res == Constant::cond_true ? tval : fval;
 288           Value new_fval = f_compare_res == Constant::cond_true ? tval : fval;
 289 
 290           _ifop_count++;
 291           if (new_tval == new_fval) {
 292             return new_tval;
 293           } else {
 294             return new IfOp(x_ifop->x(), x_ifop_cond, x_ifop->y(), new_tval, new_fval, state_before, substitutability_check);
 295           }
 296         }
 297       }
 298     } else {
 299       Constant* x_const = x->as_Constant();
 300       if (x_const != NULL) {         // x and y are constants
 301         Constant::CompareResult x_compare_res = x_const->compare(cond, y_const);
 302         // not_comparable here is a valid return in case we're comparing unloaded oop constants
 303         if (x_compare_res != Constant::not_comparable) {
 304           _ifop_count++;
 305           return x_compare_res == Constant::cond_true ? tval : fval;
 306         }
 307       }
 308     }
 309   }
 310   return new IfOp(x, cond, y, tval, fval, state_before, substitutability_check);
 311 }
 312 
 313 void Optimizer::eliminate_conditional_expressions() {
 314   // find conditional expressions & replace them with IfOps
 315   CE_Eliminator ce(ir());
 316 }
 317 
 318 class BlockMerger: public BlockClosure {
 319  private:
 320   IR* _hir;
 321   int _merge_count;              // the number of block pairs successfully merged
 322 
 323  public:
 324   BlockMerger(IR* hir)
 325   : _hir(hir)
 326   , _merge_count(0)
 327   {
 328     _hir->iterate_preorder(this);
 329     CompileLog* log = _hir->compilation()->log();
 330     if (log != NULL)
 331       log->set_context("optimize name='eliminate_blocks'");
 332   }
 333 
 334   ~BlockMerger() {
 335     CompileLog* log = _hir->compilation()->log();
 336     if (log != NULL)
 337       log->clear_context(); // skip marker if nothing was printed
 338   }
 339 
 340   bool try_merge(BlockBegin* block) {
 341     BlockEnd* end = block->end();
 342     if (end->as_Goto() != NULL) {
 343       assert(end->number_of_sux() == 1, "end must have exactly one successor");
 344       // Note: It would be sufficient to check for the number of successors (= 1)
 345       //       in order to decide if this block can be merged potentially. That
 346       //       would then also include switch statements w/ only a default case.
 347       //       However, in that case we would need to make sure the switch tag
 348       //       expression is executed if it can produce observable side effects.
 349       //       We should probably have the canonicalizer simplifying such switch
 350       //       statements and then we are sure we don't miss these merge opportunities
 351       //       here (was bug - gri 7/7/99).
 352       BlockBegin* sux = end->default_sux();
 353       if (sux->number_of_preds() == 1 && !sux->is_entry_block() && !end->is_safepoint()) {
 354         // merge the two blocks
 355 
 356 #ifdef ASSERT
 357         // verify that state at the end of block and at the beginning of sux are equal
 358         // no phi functions must be present at beginning of sux
 359         ValueStack* sux_state = sux->state();
 360         ValueStack* end_state = end->state();
 361 
 362         assert(end_state->scope() == sux_state->scope(), "scopes must match");
 363         assert(end_state->stack_size() == sux_state->stack_size(), "stack not equal");
 364         assert(end_state->locals_size() == sux_state->locals_size(), "locals not equal");
 365 
 366         int index;
 367         Value sux_value;
 368         for_each_stack_value(sux_state, index, sux_value) {
 369           assert(sux_value == end_state->stack_at(index), "stack not equal");
 370         }
 371         for_each_local_value(sux_state, index, sux_value) {
 372           assert(sux_value == end_state->local_at(index), "locals not equal");
 373         }
 374         assert(sux_state->caller_state() == end_state->caller_state(), "caller not equal");
 375 #endif
 376 
 377         // find instruction before end & append first instruction of sux block
 378         Instruction* prev = end->prev();
 379         Instruction* next = sux->next();
 380         assert(prev->as_BlockEnd() == NULL, "must not be a BlockEnd");
 381         prev->set_next(next);
 382         prev->fixup_block_pointers();
 383         sux->disconnect_from_graph();
 384         block->set_end(sux->end());
 385         // add exception handlers of deleted block, if any
 386         for (int k = 0; k < sux->number_of_exception_handlers(); k++) {
 387           BlockBegin* xhandler = sux->exception_handler_at(k);
 388           block->add_exception_handler(xhandler);
 389 
 390           // also substitute predecessor of exception handler
 391           assert(xhandler->is_predecessor(sux), "missing predecessor");
 392           xhandler->remove_predecessor(sux);
 393           if (!xhandler->is_predecessor(block)) {
 394             xhandler->add_predecessor(block);
 395           }
 396         }
 397 
 398         // debugging output
 399         _merge_count++;
 400         if (PrintBlockElimination) {
 401           tty->print_cr("%d. merged B%d & B%d (stack size = %d)",
 402                         _merge_count, block->block_id(), sux->block_id(), sux->state()->stack_size());
 403         }
 404 
 405         _hir->verify();
 406 
 407         If* if_ = block->end()->as_If();
 408         if (if_) {
 409           IfOp* ifop    = if_->x()->as_IfOp();
 410           Constant* con = if_->y()->as_Constant();
 411           bool swapped = false;
 412           if (!con || !ifop) {
 413             ifop = if_->y()->as_IfOp();
 414             con  = if_->x()->as_Constant();
 415             swapped = true;
 416           }
 417           if (con && ifop) {
 418             Constant* tval = ifop->tval()->as_Constant();
 419             Constant* fval = ifop->fval()->as_Constant();
 420             if (tval && fval) {
 421               // Find the instruction before if_, starting with ifop.
 422               // When if_ and ifop are not in the same block, prev
 423               // becomes NULL In such (rare) cases it is not
 424               // profitable to perform the optimization.
 425               Value prev = ifop;
 426               while (prev != NULL && prev->next() != if_) {
 427                 prev = prev->next();
 428               }
 429 
 430               if (prev != NULL) {
 431                 Instruction::Condition cond = if_->cond();
 432                 BlockBegin* tsux = if_->tsux();
 433                 BlockBegin* fsux = if_->fsux();
 434                 if (swapped) {
 435                   cond = Instruction::mirror(cond);
 436                 }
 437 
 438                 BlockBegin* tblock = tval->compare(cond, con, tsux, fsux);
 439                 BlockBegin* fblock = fval->compare(cond, con, tsux, fsux);
 440                 if (tblock != fblock && !if_->is_safepoint()) {
 441                   If* newif = new If(ifop->x(), ifop->cond(), false, ifop->y(),
 442                                      tblock, fblock, if_->state_before(), if_->is_safepoint(), if_->substitutability_check());
 443                   newif->set_state(if_->state()->copy());
 444 
 445                   assert(prev->next() == if_, "must be guaranteed by above search");
 446                   NOT_PRODUCT(newif->set_printable_bci(if_->printable_bci()));
 447                   prev->set_next(newif);
 448                   block->set_end(newif);
 449 
 450                   _merge_count++;
 451                   if (PrintBlockElimination) {
 452                     tty->print_cr("%d. replaced If and IfOp at end of B%d with single If", _merge_count, block->block_id());
 453                   }
 454 
 455                   _hir->verify();
 456                 }
 457               }
 458             }
 459           }
 460         }
 461 
 462         return true;
 463       }
 464     }
 465     return false;
 466   }
 467 
 468   virtual void block_do(BlockBegin* block) {
 469     _hir->verify();
 470     // repeat since the same block may merge again
 471     while (try_merge(block)) {
 472       _hir->verify();
 473     }
 474   }
 475 };
 476 
 477 
 478 void Optimizer::eliminate_blocks() {
 479   // merge blocks if possible
 480   BlockMerger bm(ir());
 481 }
 482 
 483 
 484 class NullCheckEliminator;
 485 class NullCheckVisitor: public InstructionVisitor {
 486 private:
 487   NullCheckEliminator* _nce;
 488   NullCheckEliminator* nce() { return _nce; }
 489 
 490 public:
 491   NullCheckVisitor() {}
 492 
 493   void set_eliminator(NullCheckEliminator* nce) { _nce = nce; }
 494 
 495   void do_Phi            (Phi*             x);
 496   void do_Local          (Local*           x);
 497   void do_Constant       (Constant*        x);
 498   void do_LoadField      (LoadField*       x);
 499   void do_StoreField     (StoreField*      x);
 500   void do_ArrayLength    (ArrayLength*     x);
 501   void do_LoadIndexed    (LoadIndexed*     x);
 502   void do_StoreIndexed   (StoreIndexed*    x);
 503   void do_NegateOp       (NegateOp*        x);
 504   void do_ArithmeticOp   (ArithmeticOp*    x);
 505   void do_ShiftOp        (ShiftOp*         x);
 506   void do_LogicOp        (LogicOp*         x);
 507   void do_CompareOp      (CompareOp*       x);
 508   void do_IfOp           (IfOp*            x);
 509   void do_Convert        (Convert*         x);
 510   void do_NullCheck      (NullCheck*       x);
 511   void do_TypeCast       (TypeCast*        x);
 512   void do_Invoke         (Invoke*          x);
 513   void do_NewInstance    (NewInstance*     x);
 514   void do_NewValueTypeInstance(NewValueTypeInstance* x);
 515   void do_NewTypeArray   (NewTypeArray*    x);
 516   void do_NewObjectArray (NewObjectArray*  x);
 517   void do_NewMultiArray  (NewMultiArray*   x);
 518   void do_CheckCast      (CheckCast*       x);
 519   void do_InstanceOf     (InstanceOf*      x);
 520   void do_MonitorEnter   (MonitorEnter*    x);
 521   void do_MonitorExit    (MonitorExit*     x);
 522   void do_Intrinsic      (Intrinsic*       x);
 523   void do_BlockBegin     (BlockBegin*      x);
 524   void do_Goto           (Goto*            x);
 525   void do_If             (If*              x);
 526   void do_IfInstanceOf   (IfInstanceOf*    x);
 527   void do_TableSwitch    (TableSwitch*     x);
 528   void do_LookupSwitch   (LookupSwitch*    x);
 529   void do_Return         (Return*          x);
 530   void do_Throw          (Throw*           x);
 531   void do_Base           (Base*            x);
 532   void do_OsrEntry       (OsrEntry*        x);
 533   void do_ExceptionObject(ExceptionObject* x);
 534   void do_RoundFP        (RoundFP*         x);
 535   void do_UnsafeGetRaw   (UnsafeGetRaw*    x);
 536   void do_UnsafePutRaw   (UnsafePutRaw*    x);
 537   void do_UnsafeGetObject(UnsafeGetObject* x);
 538   void do_UnsafePutObject(UnsafePutObject* x);
 539   void do_UnsafeGetAndSetObject(UnsafeGetAndSetObject* x);
 540   void do_ProfileCall    (ProfileCall*     x);
 541   void do_ProfileReturnType (ProfileReturnType*  x);
 542   void do_ProfileInvoke  (ProfileInvoke*   x);
 543   void do_RuntimeCall    (RuntimeCall*     x);
 544   void do_MemBar         (MemBar*          x);
 545   void do_RangeCheckPredicate(RangeCheckPredicate* x);
 546 #ifdef ASSERT
 547   void do_Assert         (Assert*          x);
 548 #endif
 549 };
 550 
 551 
 552 // Because of a static contained within (for the purpose of iteration
 553 // over instructions), it is only valid to have one of these active at
 554 // a time
 555 class NullCheckEliminator: public ValueVisitor {
 556  private:
 557   Optimizer*        _opt;
 558 
 559   ValueSet*         _visitable_instructions;        // Visit each instruction only once per basic block
 560   BlockList*        _work_list;                   // Basic blocks to visit
 561 
 562   bool visitable(Value x) {
 563     assert(_visitable_instructions != NULL, "check");
 564     return _visitable_instructions->contains(x);
 565   }
 566   void mark_visited(Value x) {
 567     assert(_visitable_instructions != NULL, "check");
 568     _visitable_instructions->remove(x);
 569   }
 570   void mark_visitable(Value x) {
 571     assert(_visitable_instructions != NULL, "check");
 572     _visitable_instructions->put(x);
 573   }
 574   void clear_visitable_state() {
 575     assert(_visitable_instructions != NULL, "check");
 576     _visitable_instructions->clear();
 577   }
 578 
 579   ValueSet*         _set;                         // current state, propagated to subsequent BlockBegins
 580   ValueSetList      _block_states;                // BlockBegin null-check states for all processed blocks
 581   NullCheckVisitor  _visitor;
 582   NullCheck*        _last_explicit_null_check;
 583 
 584   bool set_contains(Value x)                      { assert(_set != NULL, "check"); return _set->contains(x); }
 585   void set_put     (Value x)                      { assert(_set != NULL, "check"); _set->put(x); }
 586   void set_remove  (Value x)                      { assert(_set != NULL, "check"); _set->remove(x); }
 587 
 588   BlockList* work_list()                          { return _work_list; }
 589 
 590   void iterate_all();
 591   void iterate_one(BlockBegin* block);
 592 
 593   ValueSet* state()                               { return _set; }
 594   void      set_state_from (ValueSet* state)      { _set->set_from(state); }
 595   ValueSet* state_for      (BlockBegin* block)    { return _block_states.at(block->block_id()); }
 596   void      set_state_for  (BlockBegin* block, ValueSet* stack) { _block_states.at_put(block->block_id(), stack); }
 597   // Returns true if caused a change in the block's state.
 598   bool      merge_state_for(BlockBegin* block,
 599                             ValueSet*   incoming_state);
 600 
 601  public:
 602   // constructor
 603   NullCheckEliminator(Optimizer* opt)
 604     : _opt(opt)
 605     , _work_list(new BlockList())
 606     , _set(new ValueSet())
 607     , _block_states(BlockBegin::number_of_blocks(), BlockBegin::number_of_blocks(), NULL)
 608     , _last_explicit_null_check(NULL) {
 609     _visitable_instructions = new ValueSet();
 610     _visitor.set_eliminator(this);
 611     CompileLog* log = _opt->ir()->compilation()->log();
 612     if (log != NULL)
 613       log->set_context("optimize name='null_check_elimination'");
 614   }
 615 
 616   ~NullCheckEliminator() {
 617     CompileLog* log = _opt->ir()->compilation()->log();
 618     if (log != NULL)
 619       log->clear_context(); // skip marker if nothing was printed
 620   }
 621 
 622   Optimizer*  opt()                               { return _opt; }
 623   IR*         ir ()                               { return opt()->ir(); }
 624 
 625   // Process a graph
 626   void iterate(BlockBegin* root);
 627 
 628   void visit(Value* f);
 629 
 630   // In some situations (like NullCheck(x); getfield(x)) the debug
 631   // information from the explicit NullCheck can be used to populate
 632   // the getfield, even if the two instructions are in different
 633   // scopes; this allows implicit null checks to be used but the
 634   // correct exception information to be generated. We must clear the
 635   // last-traversed NullCheck when we reach a potentially-exception-
 636   // throwing instruction, as well as in some other cases.
 637   void        set_last_explicit_null_check(NullCheck* check) { _last_explicit_null_check = check; }
 638   NullCheck*  last_explicit_null_check()                     { return _last_explicit_null_check; }
 639   Value       last_explicit_null_check_obj()                 { return (_last_explicit_null_check
 640                                                                          ? _last_explicit_null_check->obj()
 641                                                                          : NULL); }
 642   NullCheck*  consume_last_explicit_null_check() {
 643     _last_explicit_null_check->unpin(Instruction::PinExplicitNullCheck);
 644     _last_explicit_null_check->set_can_trap(false);
 645     return _last_explicit_null_check;
 646   }
 647   void        clear_last_explicit_null_check()               { _last_explicit_null_check = NULL; }
 648 
 649   // Handlers for relevant instructions
 650   // (separated out from NullCheckVisitor for clarity)
 651 
 652   // The basic contract is that these must leave the instruction in
 653   // the desired state; must not assume anything about the state of
 654   // the instruction. We make multiple passes over some basic blocks
 655   // and the last pass is the only one whose result is valid.
 656   void handle_AccessField     (AccessField* x);
 657   void handle_ArrayLength     (ArrayLength* x);
 658   void handle_LoadIndexed     (LoadIndexed* x);
 659   void handle_StoreIndexed    (StoreIndexed* x);
 660   void handle_NullCheck       (NullCheck* x);
 661   void handle_Invoke          (Invoke* x);
 662   void handle_NewInstance     (NewInstance* x);
 663   void handle_NewValueTypeInstance(NewValueTypeInstance* x);
 664   void handle_NewArray        (NewArray* x);
 665   void handle_AccessMonitor   (AccessMonitor* x);
 666   void handle_Intrinsic       (Intrinsic* x);
 667   void handle_ExceptionObject (ExceptionObject* x);
 668   void handle_Phi             (Phi* x);
 669   void handle_ProfileCall     (ProfileCall* x);
 670   void handle_ProfileReturnType (ProfileReturnType* x);
 671 };
 672 
 673 
 674 // NEEDS_CLEANUP
 675 // There may be other instructions which need to clear the last
 676 // explicit null check. Anything across which we can not hoist the
 677 // debug information for a NullCheck instruction must clear it. It
 678 // might be safer to pattern match "NullCheck ; {AccessField,
 679 // ArrayLength, LoadIndexed}" but it is more easily structured this way.
 680 // Should test to see performance hit of clearing it for all handlers
 681 // with empty bodies below. If it is negligible then we should leave
 682 // that in for safety, otherwise should think more about it.
 683 void NullCheckVisitor::do_Phi            (Phi*             x) { nce()->handle_Phi(x);      }
 684 void NullCheckVisitor::do_Local          (Local*           x) {}
 685 void NullCheckVisitor::do_Constant       (Constant*        x) { /* FIXME: handle object constants */ }
 686 void NullCheckVisitor::do_LoadField      (LoadField*       x) { nce()->handle_AccessField(x); }
 687 void NullCheckVisitor::do_StoreField     (StoreField*      x) { nce()->handle_AccessField(x); }
 688 void NullCheckVisitor::do_ArrayLength    (ArrayLength*     x) { nce()->handle_ArrayLength(x); }
 689 void NullCheckVisitor::do_LoadIndexed    (LoadIndexed*     x) { nce()->handle_LoadIndexed(x); }
 690 void NullCheckVisitor::do_StoreIndexed   (StoreIndexed*    x) { nce()->handle_StoreIndexed(x); }
 691 void NullCheckVisitor::do_NegateOp       (NegateOp*        x) {}
 692 void NullCheckVisitor::do_ArithmeticOp   (ArithmeticOp*    x) { if (x->can_trap()) nce()->clear_last_explicit_null_check(); }
 693 void NullCheckVisitor::do_ShiftOp        (ShiftOp*         x) {}
 694 void NullCheckVisitor::do_LogicOp        (LogicOp*         x) {}
 695 void NullCheckVisitor::do_CompareOp      (CompareOp*       x) {}
 696 void NullCheckVisitor::do_IfOp           (IfOp*            x) {}
 697 void NullCheckVisitor::do_Convert        (Convert*         x) {}
 698 void NullCheckVisitor::do_NullCheck      (NullCheck*       x) { nce()->handle_NullCheck(x); }
 699 void NullCheckVisitor::do_TypeCast       (TypeCast*        x) {}
 700 void NullCheckVisitor::do_Invoke         (Invoke*          x) { nce()->handle_Invoke(x); }
 701 void NullCheckVisitor::do_NewInstance    (NewInstance*     x) { nce()->handle_NewInstance(x); }
 702 void NullCheckVisitor::do_NewValueTypeInstance(NewValueTypeInstance*     x) { nce()->handle_NewValueTypeInstance(x); }
 703 void NullCheckVisitor::do_NewTypeArray   (NewTypeArray*    x) { nce()->handle_NewArray(x); }
 704 void NullCheckVisitor::do_NewObjectArray (NewObjectArray*  x) { nce()->handle_NewArray(x); }
 705 void NullCheckVisitor::do_NewMultiArray  (NewMultiArray*   x) { nce()->handle_NewArray(x); }
 706 void NullCheckVisitor::do_CheckCast      (CheckCast*       x) { nce()->clear_last_explicit_null_check(); }
 707 void NullCheckVisitor::do_InstanceOf     (InstanceOf*      x) {}
 708 void NullCheckVisitor::do_MonitorEnter   (MonitorEnter*    x) { nce()->handle_AccessMonitor(x); }
 709 void NullCheckVisitor::do_MonitorExit    (MonitorExit*     x) { nce()->handle_AccessMonitor(x); }
 710 void NullCheckVisitor::do_Intrinsic      (Intrinsic*       x) { nce()->handle_Intrinsic(x);     }
 711 void NullCheckVisitor::do_BlockBegin     (BlockBegin*      x) {}
 712 void NullCheckVisitor::do_Goto           (Goto*            x) {}
 713 void NullCheckVisitor::do_If             (If*              x) {}
 714 void NullCheckVisitor::do_IfInstanceOf   (IfInstanceOf*    x) {}
 715 void NullCheckVisitor::do_TableSwitch    (TableSwitch*     x) {}
 716 void NullCheckVisitor::do_LookupSwitch   (LookupSwitch*    x) {}
 717 void NullCheckVisitor::do_Return         (Return*          x) {}
 718 void NullCheckVisitor::do_Throw          (Throw*           x) { nce()->clear_last_explicit_null_check(); }
 719 void NullCheckVisitor::do_Base           (Base*            x) {}
 720 void NullCheckVisitor::do_OsrEntry       (OsrEntry*        x) {}
 721 void NullCheckVisitor::do_ExceptionObject(ExceptionObject* x) { nce()->handle_ExceptionObject(x); }
 722 void NullCheckVisitor::do_RoundFP        (RoundFP*         x) {}
 723 void NullCheckVisitor::do_UnsafeGetRaw   (UnsafeGetRaw*    x) {}
 724 void NullCheckVisitor::do_UnsafePutRaw   (UnsafePutRaw*    x) {}
 725 void NullCheckVisitor::do_UnsafeGetObject(UnsafeGetObject* x) {}
 726 void NullCheckVisitor::do_UnsafePutObject(UnsafePutObject* x) {}
 727 void NullCheckVisitor::do_UnsafeGetAndSetObject(UnsafeGetAndSetObject* x) {}
 728 void NullCheckVisitor::do_ProfileCall    (ProfileCall*     x) { nce()->clear_last_explicit_null_check();
 729                                                                 nce()->handle_ProfileCall(x); }
 730 void NullCheckVisitor::do_ProfileReturnType (ProfileReturnType* x) { nce()->handle_ProfileReturnType(x); }
 731 void NullCheckVisitor::do_ProfileInvoke  (ProfileInvoke*   x) {}
 732 void NullCheckVisitor::do_RuntimeCall    (RuntimeCall*     x) {}
 733 void NullCheckVisitor::do_MemBar         (MemBar*          x) {}
 734 void NullCheckVisitor::do_RangeCheckPredicate(RangeCheckPredicate* x) {}
 735 #ifdef ASSERT
 736 void NullCheckVisitor::do_Assert         (Assert*          x) {}
 737 #endif
 738 
 739 void NullCheckEliminator::visit(Value* p) {
 740   assert(*p != NULL, "should not find NULL instructions");
 741   if (visitable(*p)) {
 742     mark_visited(*p);
 743     (*p)->visit(&_visitor);
 744   }
 745 }
 746 
 747 bool NullCheckEliminator::merge_state_for(BlockBegin* block, ValueSet* incoming_state) {
 748   ValueSet* state = state_for(block);
 749   if (state == NULL) {
 750     state = incoming_state->copy();
 751     set_state_for(block, state);
 752     return true;
 753   } else {
 754     bool changed = state->set_intersect(incoming_state);
 755     if (PrintNullCheckElimination && changed) {
 756       tty->print_cr("Block %d's null check state changed", block->block_id());
 757     }
 758     return changed;
 759   }
 760 }
 761 
 762 
 763 void NullCheckEliminator::iterate_all() {
 764   while (work_list()->length() > 0) {
 765     iterate_one(work_list()->pop());
 766   }
 767 }
 768 
 769 
 770 void NullCheckEliminator::iterate_one(BlockBegin* block) {
 771   clear_visitable_state();
 772   // clear out an old explicit null checks
 773   set_last_explicit_null_check(NULL);
 774 
 775   if (PrintNullCheckElimination) {
 776     tty->print_cr(" ...iterating block %d in null check elimination for %s::%s%s",
 777                   block->block_id(),
 778                   ir()->method()->holder()->name()->as_utf8(),
 779                   ir()->method()->name()->as_utf8(),
 780                   ir()->method()->signature()->as_symbol()->as_utf8());
 781   }
 782 
 783   // Create new state if none present (only happens at root)
 784   if (state_for(block) == NULL) {
 785     ValueSet* tmp_state = new ValueSet();
 786     set_state_for(block, tmp_state);
 787     // Initial state is that local 0 (receiver) is non-null for
 788     // non-static methods
 789     ValueStack* stack  = block->state();
 790     IRScope*    scope  = stack->scope();
 791     ciMethod*   method = scope->method();
 792     if (!method->is_static()) {
 793       Local* local0 = stack->local_at(0)->as_Local();
 794       assert(local0 != NULL, "must be");
 795       assert(local0->type() == objectType, "invalid type of receiver");
 796 
 797       if (local0 != NULL) {
 798         // Local 0 is used in this scope
 799         tmp_state->put(local0);
 800         if (PrintNullCheckElimination) {
 801           tty->print_cr("Local 0 (value %d) proven non-null upon entry", local0->id());
 802         }
 803       }
 804     }
 805   }
 806 
 807   // Must copy block's state to avoid mutating it during iteration
 808   // through the block -- otherwise "not-null" states can accidentally
 809   // propagate "up" through the block during processing of backward
 810   // branches and algorithm is incorrect (and does not converge)
 811   set_state_from(state_for(block));
 812 
 813   // allow visiting of Phis belonging to this block
 814   for_each_phi_fun(block, phi,
 815                    mark_visitable(phi);
 816                    );
 817 
 818   BlockEnd* e = block->end();
 819   assert(e != NULL, "incomplete graph");
 820   int i;
 821 
 822   // Propagate the state before this block into the exception
 823   // handlers.  They aren't true successors since we aren't guaranteed
 824   // to execute the whole block before executing them.  Also putting
 825   // them on first seems to help reduce the amount of iteration to
 826   // reach a fixed point.
 827   for (i = 0; i < block->number_of_exception_handlers(); i++) {
 828     BlockBegin* next = block->exception_handler_at(i);
 829     if (merge_state_for(next, state())) {
 830       if (!work_list()->contains(next)) {
 831         work_list()->push(next);
 832       }
 833     }
 834   }
 835 
 836   // Iterate through block, updating state.
 837   for (Instruction* instr = block; instr != NULL; instr = instr->next()) {
 838     // Mark instructions in this block as visitable as they are seen
 839     // in the instruction list.  This keeps the iteration from
 840     // visiting instructions which are references in other blocks or
 841     // visiting instructions more than once.
 842     mark_visitable(instr);
 843     if (instr->is_pinned() || instr->can_trap() || (instr->as_NullCheck() != NULL)) {
 844       mark_visited(instr);
 845       instr->input_values_do(this);
 846       instr->visit(&_visitor);
 847     }
 848   }
 849 
 850   // Propagate state to successors if necessary
 851   for (i = 0; i < e->number_of_sux(); i++) {
 852     BlockBegin* next = e->sux_at(i);
 853     if (merge_state_for(next, state())) {
 854       if (!work_list()->contains(next)) {
 855         work_list()->push(next);
 856       }
 857     }
 858   }
 859 }
 860 
 861 
 862 void NullCheckEliminator::iterate(BlockBegin* block) {
 863   work_list()->push(block);
 864   iterate_all();
 865 }
 866 
 867 void NullCheckEliminator::handle_AccessField(AccessField* x) {
 868   if (x->is_static()) {
 869     if (x->as_LoadField() != NULL) {
 870       // If the field is a non-null static final object field (as is
 871       // often the case for sun.misc.Unsafe), put this LoadField into
 872       // the non-null map
 873       ciField* field = x->field();
 874       if (field->is_constant()) {
 875         ciConstant field_val = field->constant_value();
 876         BasicType field_type = field_val.basic_type();
 877         if (field_type == T_OBJECT || field_type == T_ARRAY || field_type == T_VALUETYPE) {
 878           ciObject* obj_val = field_val.as_object();
 879           if (!obj_val->is_null_object()) {
 880             if (PrintNullCheckElimination) {
 881               tty->print_cr("AccessField %d proven non-null by static final non-null oop check",
 882                             x->id());
 883             }
 884             set_put(x);
 885           }
 886         }
 887       }
 888     }
 889     // Be conservative
 890     clear_last_explicit_null_check();
 891     return;
 892   }
 893 
 894   Value obj = x->obj();
 895   if (set_contains(obj)) {
 896     // Value is non-null => update AccessField
 897     if (last_explicit_null_check_obj() == obj && !x->needs_patching()) {
 898       x->set_explicit_null_check(consume_last_explicit_null_check());
 899       x->set_needs_null_check(true);
 900       if (PrintNullCheckElimination) {
 901         tty->print_cr("Folded NullCheck %d into AccessField %d's null check for value %d",
 902                       x->explicit_null_check()->id(), x->id(), obj->id());
 903       }
 904     } else {
 905       x->set_explicit_null_check(NULL);
 906       x->set_needs_null_check(false);
 907       if (PrintNullCheckElimination) {
 908         tty->print_cr("Eliminated AccessField %d's null check for value %d", x->id(), obj->id());
 909       }
 910     }
 911   } else {
 912     set_put(obj);
 913     if (PrintNullCheckElimination) {
 914       tty->print_cr("AccessField %d of value %d proves value to be non-null", x->id(), obj->id());
 915     }
 916     // Ensure previous passes do not cause wrong state
 917     x->set_needs_null_check(true);
 918     x->set_explicit_null_check(NULL);
 919   }
 920   clear_last_explicit_null_check();
 921 }
 922 
 923 
 924 void NullCheckEliminator::handle_ArrayLength(ArrayLength* x) {
 925   Value array = x->array();
 926   if (set_contains(array)) {
 927     // Value is non-null => update AccessArray
 928     if (last_explicit_null_check_obj() == array) {
 929       x->set_explicit_null_check(consume_last_explicit_null_check());
 930       x->set_needs_null_check(true);
 931       if (PrintNullCheckElimination) {
 932         tty->print_cr("Folded NullCheck %d into ArrayLength %d's null check for value %d",
 933                       x->explicit_null_check()->id(), x->id(), array->id());
 934       }
 935     } else {
 936       x->set_explicit_null_check(NULL);
 937       x->set_needs_null_check(false);
 938       if (PrintNullCheckElimination) {
 939         tty->print_cr("Eliminated ArrayLength %d's null check for value %d", x->id(), array->id());
 940       }
 941     }
 942   } else {
 943     set_put(array);
 944     if (PrintNullCheckElimination) {
 945       tty->print_cr("ArrayLength %d of value %d proves value to be non-null", x->id(), array->id());
 946     }
 947     // Ensure previous passes do not cause wrong state
 948     x->set_needs_null_check(true);
 949     x->set_explicit_null_check(NULL);
 950   }
 951   clear_last_explicit_null_check();
 952 }
 953 
 954 
 955 void NullCheckEliminator::handle_LoadIndexed(LoadIndexed* x) {
 956   Value array = x->array();
 957   if (set_contains(array)) {
 958     // Value is non-null => update AccessArray
 959     if (last_explicit_null_check_obj() == array) {
 960       x->set_explicit_null_check(consume_last_explicit_null_check());
 961       x->set_needs_null_check(true);
 962       if (PrintNullCheckElimination) {
 963         tty->print_cr("Folded NullCheck %d into LoadIndexed %d's null check for value %d",
 964                       x->explicit_null_check()->id(), x->id(), array->id());
 965       }
 966     } else {
 967       x->set_explicit_null_check(NULL);
 968       x->set_needs_null_check(false);
 969       if (PrintNullCheckElimination) {
 970         tty->print_cr("Eliminated LoadIndexed %d's null check for value %d", x->id(), array->id());
 971       }
 972     }
 973   } else {
 974     set_put(array);
 975     if (PrintNullCheckElimination) {
 976       tty->print_cr("LoadIndexed %d of value %d proves value to be non-null", x->id(), array->id());
 977     }
 978     // Ensure previous passes do not cause wrong state
 979     x->set_needs_null_check(true);
 980     x->set_explicit_null_check(NULL);
 981   }
 982   clear_last_explicit_null_check();
 983 }
 984 
 985 
 986 void NullCheckEliminator::handle_StoreIndexed(StoreIndexed* x) {
 987   Value array = x->array();
 988   if (set_contains(array)) {
 989     // Value is non-null => update AccessArray
 990     if (PrintNullCheckElimination) {
 991       tty->print_cr("Eliminated StoreIndexed %d's null check for value %d", x->id(), array->id());
 992     }
 993     x->set_needs_null_check(false);
 994   } else {
 995     set_put(array);
 996     if (PrintNullCheckElimination) {
 997       tty->print_cr("StoreIndexed %d of value %d proves value to be non-null", x->id(), array->id());
 998     }
 999     // Ensure previous passes do not cause wrong state
1000     x->set_needs_null_check(true);
1001   }
1002   clear_last_explicit_null_check();
1003 }
1004 
1005 
1006 void NullCheckEliminator::handle_NullCheck(NullCheck* x) {
1007   Value obj = x->obj();
1008   if (set_contains(obj)) {
1009     // Already proven to be non-null => this NullCheck is useless
1010     if (PrintNullCheckElimination) {
1011       tty->print_cr("Eliminated NullCheck %d for value %d", x->id(), obj->id());
1012     }
1013     // Don't unpin since that may shrink obj's live range and make it unavailable for debug info.
1014     // The code generator won't emit LIR for a NullCheck that cannot trap.
1015     x->set_can_trap(false);
1016   } else {
1017     // May be null => add to map and set last explicit NullCheck
1018     x->set_can_trap(true);
1019     // make sure it's pinned if it can trap
1020     x->pin(Instruction::PinExplicitNullCheck);
1021     set_put(obj);
1022     set_last_explicit_null_check(x);
1023     if (PrintNullCheckElimination) {
1024       tty->print_cr("NullCheck %d of value %d proves value to be non-null", x->id(), obj->id());
1025     }
1026   }
1027 }
1028 
1029 
1030 void NullCheckEliminator::handle_Invoke(Invoke* x) {
1031   if (!x->has_receiver()) {
1032     // Be conservative
1033     clear_last_explicit_null_check();
1034     return;
1035   }
1036 
1037   Value recv = x->receiver();
1038   if (!set_contains(recv)) {
1039     set_put(recv);
1040     if (PrintNullCheckElimination) {
1041       tty->print_cr("Invoke %d of value %d proves value to be non-null", x->id(), recv->id());
1042     }
1043   }
1044   clear_last_explicit_null_check();
1045 }
1046 
1047 
1048 void NullCheckEliminator::handle_NewInstance(NewInstance* x) {
1049   set_put(x);
1050   if (PrintNullCheckElimination) {
1051     tty->print_cr("NewInstance %d is non-null", x->id());
1052   }
1053 }
1054 
1055 void NullCheckEliminator::handle_NewValueTypeInstance(NewValueTypeInstance* x) {
1056   set_put(x);
1057   if (PrintNullCheckElimination) {
1058     tty->print_cr("NewValueTypeInstance %d is non-null", x->id());
1059   }
1060 }
1061 
1062 
1063 void NullCheckEliminator::handle_NewArray(NewArray* x) {
1064   set_put(x);
1065   if (PrintNullCheckElimination) {
1066     tty->print_cr("NewArray %d is non-null", x->id());
1067   }
1068 }
1069 
1070 
1071 void NullCheckEliminator::handle_ExceptionObject(ExceptionObject* x) {
1072   set_put(x);
1073   if (PrintNullCheckElimination) {
1074     tty->print_cr("ExceptionObject %d is non-null", x->id());
1075   }
1076 }
1077 
1078 
1079 void NullCheckEliminator::handle_AccessMonitor(AccessMonitor* x) {
1080   Value obj = x->obj();
1081   if (set_contains(obj)) {
1082     // Value is non-null => update AccessMonitor
1083     if (PrintNullCheckElimination) {
1084       tty->print_cr("Eliminated AccessMonitor %d's null check for value %d", x->id(), obj->id());
1085     }
1086     x->set_needs_null_check(false);
1087   } else {
1088     set_put(obj);
1089     if (PrintNullCheckElimination) {
1090       tty->print_cr("AccessMonitor %d of value %d proves value to be non-null", x->id(), obj->id());
1091     }
1092     // Ensure previous passes do not cause wrong state
1093     x->set_needs_null_check(true);
1094   }
1095   clear_last_explicit_null_check();
1096 }
1097 
1098 
1099 void NullCheckEliminator::handle_Intrinsic(Intrinsic* x) {
1100   if (!x->has_receiver()) {
1101     if (x->id() == vmIntrinsics::_arraycopy) {
1102       for (int i = 0; i < x->number_of_arguments(); i++) {
1103         x->set_arg_needs_null_check(i, !set_contains(x->argument_at(i)));
1104       }
1105     }
1106 
1107     // Be conservative
1108     clear_last_explicit_null_check();
1109     return;
1110   }
1111 
1112   Value recv = x->receiver();
1113   if (set_contains(recv)) {
1114     // Value is non-null => update Intrinsic
1115     if (PrintNullCheckElimination) {
1116       tty->print_cr("Eliminated Intrinsic %d's null check for value %d", x->id(), recv->id());
1117     }
1118     x->set_needs_null_check(false);
1119   } else {
1120     set_put(recv);
1121     if (PrintNullCheckElimination) {
1122       tty->print_cr("Intrinsic %d of value %d proves value to be non-null", x->id(), recv->id());
1123     }
1124     // Ensure previous passes do not cause wrong state
1125     x->set_needs_null_check(true);
1126   }
1127   clear_last_explicit_null_check();
1128 }
1129 
1130 
1131 void NullCheckEliminator::handle_Phi(Phi* x) {
1132   int i;
1133   bool all_non_null = true;
1134   if (x->is_illegal()) {
1135     all_non_null = false;
1136   } else {
1137     for (i = 0; i < x->operand_count(); i++) {
1138       Value input = x->operand_at(i);
1139       if (!set_contains(input)) {
1140         all_non_null = false;
1141       }
1142     }
1143   }
1144 
1145   if (all_non_null) {
1146     // Value is non-null => update Phi
1147     if (PrintNullCheckElimination) {
1148       tty->print_cr("Eliminated Phi %d's null check for phifun because all inputs are non-null", x->id());
1149     }
1150     x->set_needs_null_check(false);
1151   } else if (set_contains(x)) {
1152     set_remove(x);
1153   }
1154 }
1155 
1156 void NullCheckEliminator::handle_ProfileCall(ProfileCall* x) {
1157   for (int i = 0; i < x->nb_profiled_args(); i++) {
1158     x->set_arg_needs_null_check(i, !set_contains(x->profiled_arg_at(i)));
1159   }
1160 }
1161 
1162 void NullCheckEliminator::handle_ProfileReturnType(ProfileReturnType* x) {
1163   x->set_needs_null_check(!set_contains(x->ret()));
1164 }
1165 
1166 void Optimizer::eliminate_null_checks() {
1167   ResourceMark rm;
1168 
1169   NullCheckEliminator nce(this);
1170 
1171   if (PrintNullCheckElimination) {
1172     tty->print_cr("Starting null check elimination for method %s::%s%s",
1173                   ir()->method()->holder()->name()->as_utf8(),
1174                   ir()->method()->name()->as_utf8(),
1175                   ir()->method()->signature()->as_symbol()->as_utf8());
1176   }
1177 
1178   // Apply to graph
1179   nce.iterate(ir()->start());
1180 
1181   // walk over the graph looking for exception
1182   // handlers and iterate over them as well
1183   int nblocks = BlockBegin::number_of_blocks();
1184   BlockList blocks(nblocks);
1185   boolArray visited_block(nblocks, nblocks, false);
1186 
1187   blocks.push(ir()->start());
1188   visited_block.at_put(ir()->start()->block_id(), true);
1189   for (int i = 0; i < blocks.length(); i++) {
1190     BlockBegin* b = blocks.at(i);
1191     // exception handlers need to be treated as additional roots
1192     for (int e = b->number_of_exception_handlers(); e-- > 0; ) {
1193       BlockBegin* excp = b->exception_handler_at(e);
1194       int id = excp->block_id();
1195       if (!visited_block.at(id)) {
1196         blocks.push(excp);
1197         visited_block.at_put(id, true);
1198         nce.iterate(excp);
1199       }
1200     }
1201     // traverse successors
1202     BlockEnd *end = b->end();
1203     for (int s = end->number_of_sux(); s-- > 0; ) {
1204       BlockBegin* next = end->sux_at(s);
1205       int id = next->block_id();
1206       if (!visited_block.at(id)) {
1207         blocks.push(next);
1208         visited_block.at_put(id, true);
1209       }
1210     }
1211   }
1212 
1213 
1214   if (PrintNullCheckElimination) {
1215     tty->print_cr("Done with null check elimination for method %s::%s%s",
1216                   ir()->method()->holder()->name()->as_utf8(),
1217                   ir()->method()->name()->as_utf8(),
1218                   ir()->method()->signature()->as_symbol()->as_utf8());
1219   }
1220 }