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