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