1 /*
   2  * Copyright (c) 1999, 2024, 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_CFGPrinter.hpp"
  27 #include "c1/c1_Canonicalizer.hpp"
  28 #include "c1/c1_Compilation.hpp"
  29 #include "c1/c1_GraphBuilder.hpp"
  30 #include "c1/c1_InstructionPrinter.hpp"
  31 #include "ci/ciCallSite.hpp"
  32 #include "ci/ciField.hpp"
  33 #include "ci/ciFlatArrayKlass.hpp"
  34 #include "ci/ciInlineKlass.hpp"
  35 #include "ci/ciKlass.hpp"
  36 #include "ci/ciMemberName.hpp"
  37 #include "ci/ciSymbols.hpp"
  38 #include "ci/ciUtilities.inline.hpp"
  39 #include "classfile/javaClasses.hpp"
  40 #include "compiler/compilationPolicy.hpp"
  41 #include "compiler/compileBroker.hpp"
  42 #include "compiler/compilerEvent.hpp"
  43 #include "interpreter/bytecode.hpp"
  44 #include "jfr/jfrEvents.hpp"
  45 #include "memory/resourceArea.hpp"
  46 #include "oops/oop.inline.hpp"
  47 #include "runtime/sharedRuntime.hpp"
  48 #include "runtime/vm_version.hpp"
  49 #include "utilities/bitMap.inline.hpp"
  50 #include "utilities/checkedCast.hpp"
  51 #include "utilities/powerOfTwo.hpp"
  52 #include "utilities/macros.hpp"
  53 #if INCLUDE_JFR
  54 #include "jfr/jfr.hpp"
  55 #endif
  56 
  57 class BlockListBuilder {
  58  private:
  59   Compilation* _compilation;
  60   IRScope*     _scope;
  61 
  62   BlockList    _blocks;                // internal list of all blocks
  63   BlockList*   _bci2block;             // mapping from bci to blocks for GraphBuilder
  64   GrowableArray<BlockList> _bci2block_successors; // Mapping bcis to their blocks successors while we dont have a blockend
  65 
  66   // fields used by mark_loops
  67   ResourceBitMap _active;              // for iteration of control flow graph
  68   ResourceBitMap _visited;             // for iteration of control flow graph
  69   GrowableArray<ResourceBitMap> _loop_map; // caches the information if a block is contained in a loop
  70   int            _next_loop_index;     // next free loop number
  71   int            _next_block_number;   // for reverse postorder numbering of blocks
  72   int            _block_id_start;
  73 
  74   int           bit_number(int block_id) const   { return block_id - _block_id_start; }
  75   // accessors
  76   Compilation*  compilation() const              { return _compilation; }
  77   IRScope*      scope() const                    { return _scope; }
  78   ciMethod*     method() const                   { return scope()->method(); }
  79   XHandlers*    xhandlers() const                { return scope()->xhandlers(); }
  80 
  81   // unified bailout support
  82   void          bailout(const char* msg) const   { compilation()->bailout(msg); }
  83   bool          bailed_out() const               { return compilation()->bailed_out(); }
  84 
  85   // helper functions
  86   BlockBegin* make_block_at(int bci, BlockBegin* predecessor);
  87   void handle_exceptions(BlockBegin* current, int cur_bci);
  88   void handle_jsr(BlockBegin* current, int sr_bci, int next_bci);
  89   void store_one(BlockBegin* current, int local);
  90   void store_two(BlockBegin* current, int local);
  91   void set_entries(int osr_bci);
  92   void set_leaders();
  93 
  94   void make_loop_header(BlockBegin* block);
  95   void mark_loops();
  96   BitMap& mark_loops(BlockBegin* b, bool in_subroutine);
  97 
  98   // debugging
  99 #ifndef PRODUCT
 100   void print();
 101 #endif
 102 
 103   int number_of_successors(BlockBegin* block);
 104   BlockBegin* successor_at(BlockBegin* block, int i);
 105   void add_successor(BlockBegin* block, BlockBegin* sux);
 106   bool is_successor(BlockBegin* block, BlockBegin* sux);
 107 
 108  public:
 109   // creation
 110   BlockListBuilder(Compilation* compilation, IRScope* scope, int osr_bci);
 111 
 112   // accessors for GraphBuilder
 113   BlockList*    bci2block() const                { return _bci2block; }
 114 };
 115 
 116 
 117 // Implementation of BlockListBuilder
 118 
 119 BlockListBuilder::BlockListBuilder(Compilation* compilation, IRScope* scope, int osr_bci)
 120  : _compilation(compilation)
 121  , _scope(scope)
 122  , _blocks(16)
 123  , _bci2block(new BlockList(scope->method()->code_size(), nullptr))
 124  , _bci2block_successors(scope->method()->code_size())
 125  , _active()         // size not known yet
 126  , _visited()        // size not known yet
 127  , _loop_map() // size not known yet
 128  , _next_loop_index(0)
 129  , _next_block_number(0)
 130  , _block_id_start(0)
 131 {
 132   set_entries(osr_bci);
 133   set_leaders();
 134   CHECK_BAILOUT();
 135 
 136   mark_loops();
 137   NOT_PRODUCT(if (PrintInitialBlockList) print());
 138 
 139   // _bci2block still contains blocks with _end == null and > 0 sux in _bci2block_successors.
 140 
 141 #ifndef PRODUCT
 142   if (PrintCFGToFile) {
 143     stringStream title;
 144     title.print("BlockListBuilder ");
 145     scope->method()->print_name(&title);
 146     CFGPrinter::print_cfg(_bci2block, title.freeze(), false, false);
 147   }
 148 #endif
 149 }
 150 
 151 
 152 void BlockListBuilder::set_entries(int osr_bci) {
 153   // generate start blocks
 154   BlockBegin* std_entry = make_block_at(0, nullptr);
 155   if (scope()->caller() == nullptr) {
 156     std_entry->set(BlockBegin::std_entry_flag);
 157   }
 158   if (osr_bci != -1) {
 159     BlockBegin* osr_entry = make_block_at(osr_bci, nullptr);
 160     osr_entry->set(BlockBegin::osr_entry_flag);
 161   }
 162 
 163   // generate exception entry blocks
 164   XHandlers* list = xhandlers();
 165   const int n = list->length();
 166   for (int i = 0; i < n; i++) {
 167     XHandler* h = list->handler_at(i);
 168     BlockBegin* entry = make_block_at(h->handler_bci(), nullptr);
 169     entry->set(BlockBegin::exception_entry_flag);
 170     h->set_entry_block(entry);
 171   }
 172 }
 173 
 174 
 175 BlockBegin* BlockListBuilder::make_block_at(int cur_bci, BlockBegin* predecessor) {
 176   assert(method()->bci_block_start().at(cur_bci), "wrong block starts of MethodLivenessAnalyzer");
 177 
 178   BlockBegin* block = _bci2block->at(cur_bci);
 179   if (block == nullptr) {
 180     block = new BlockBegin(cur_bci);
 181     block->init_stores_to_locals(method()->max_locals());
 182     _bci2block->at_put(cur_bci, block);
 183     _bci2block_successors.at_put_grow(cur_bci, BlockList());
 184     _blocks.append(block);
 185 
 186     assert(predecessor == nullptr || predecessor->bci() < cur_bci, "targets for backward branches must already exist");
 187   }
 188 
 189   if (predecessor != nullptr) {
 190     if (block->is_set(BlockBegin::exception_entry_flag)) {
 191       BAILOUT_("Exception handler can be reached by both normal and exceptional control flow", block);
 192     }
 193 
 194     add_successor(predecessor, block);
 195     block->increment_total_preds();
 196   }
 197 
 198   return block;
 199 }
 200 
 201 
 202 inline void BlockListBuilder::store_one(BlockBegin* current, int local) {
 203   current->stores_to_locals().set_bit(local);
 204 }
 205 inline void BlockListBuilder::store_two(BlockBegin* current, int local) {
 206   store_one(current, local);
 207   store_one(current, local + 1);
 208 }
 209 
 210 
 211 void BlockListBuilder::handle_exceptions(BlockBegin* current, int cur_bci) {
 212   // Draws edges from a block to its exception handlers
 213   XHandlers* list = xhandlers();
 214   const int n = list->length();
 215 
 216   for (int i = 0; i < n; i++) {
 217     XHandler* h = list->handler_at(i);
 218 
 219     if (h->covers(cur_bci)) {
 220       BlockBegin* entry = h->entry_block();
 221       assert(entry != nullptr && entry == _bci2block->at(h->handler_bci()), "entry must be set");
 222       assert(entry->is_set(BlockBegin::exception_entry_flag), "flag must be set");
 223 
 224       // add each exception handler only once
 225       if(!is_successor(current, entry)) {
 226         add_successor(current, entry);
 227         entry->increment_total_preds();
 228       }
 229 
 230       // stop when reaching catchall
 231       if (h->catch_type() == 0) break;
 232     }
 233   }
 234 }
 235 
 236 void BlockListBuilder::handle_jsr(BlockBegin* current, int sr_bci, int next_bci) {
 237   if (next_bci < method()->code_size()) {
 238     // start a new block after jsr-bytecode and link this block into cfg
 239     make_block_at(next_bci, current);
 240   }
 241 
 242   // start a new block at the subroutine entry at mark it with special flag
 243   BlockBegin* sr_block = make_block_at(sr_bci, current);
 244   if (!sr_block->is_set(BlockBegin::subroutine_entry_flag)) {
 245     sr_block->set(BlockBegin::subroutine_entry_flag);
 246   }
 247 }
 248 
 249 
 250 void BlockListBuilder::set_leaders() {
 251   bool has_xhandlers = xhandlers()->has_handlers();
 252   BlockBegin* current = nullptr;
 253 
 254   // The information which bci starts a new block simplifies the analysis
 255   // Without it, backward branches could jump to a bci where no block was created
 256   // during bytecode iteration. This would require the creation of a new block at the
 257   // branch target and a modification of the successor lists.
 258   const BitMap& bci_block_start = method()->bci_block_start();
 259 
 260   int end_bci = method()->code_size();
 261 
 262   ciBytecodeStream s(method());
 263   while (s.next() != ciBytecodeStream::EOBC()) {
 264     int cur_bci = s.cur_bci();
 265 
 266     if (bci_block_start.at(cur_bci)) {
 267       current = make_block_at(cur_bci, current);
 268     }
 269     assert(current != nullptr, "must have current block");
 270 
 271     if (has_xhandlers && GraphBuilder::can_trap(method(), s.cur_bc())) {
 272       handle_exceptions(current, cur_bci);
 273     }
 274 
 275     switch (s.cur_bc()) {
 276       // track stores to local variables for selective creation of phi functions
 277       case Bytecodes::_iinc:     store_one(current, s.get_index()); break;
 278       case Bytecodes::_istore:   store_one(current, s.get_index()); break;
 279       case Bytecodes::_lstore:   store_two(current, s.get_index()); break;
 280       case Bytecodes::_fstore:   store_one(current, s.get_index()); break;
 281       case Bytecodes::_dstore:   store_two(current, s.get_index()); break;
 282       case Bytecodes::_astore:   store_one(current, s.get_index()); break;
 283       case Bytecodes::_istore_0: store_one(current, 0); break;
 284       case Bytecodes::_istore_1: store_one(current, 1); break;
 285       case Bytecodes::_istore_2: store_one(current, 2); break;
 286       case Bytecodes::_istore_3: store_one(current, 3); break;
 287       case Bytecodes::_lstore_0: store_two(current, 0); break;
 288       case Bytecodes::_lstore_1: store_two(current, 1); break;
 289       case Bytecodes::_lstore_2: store_two(current, 2); break;
 290       case Bytecodes::_lstore_3: store_two(current, 3); break;
 291       case Bytecodes::_fstore_0: store_one(current, 0); break;
 292       case Bytecodes::_fstore_1: store_one(current, 1); break;
 293       case Bytecodes::_fstore_2: store_one(current, 2); break;
 294       case Bytecodes::_fstore_3: store_one(current, 3); break;
 295       case Bytecodes::_dstore_0: store_two(current, 0); break;
 296       case Bytecodes::_dstore_1: store_two(current, 1); break;
 297       case Bytecodes::_dstore_2: store_two(current, 2); break;
 298       case Bytecodes::_dstore_3: store_two(current, 3); break;
 299       case Bytecodes::_astore_0: store_one(current, 0); break;
 300       case Bytecodes::_astore_1: store_one(current, 1); break;
 301       case Bytecodes::_astore_2: store_one(current, 2); break;
 302       case Bytecodes::_astore_3: store_one(current, 3); break;
 303 
 304       // track bytecodes that affect the control flow
 305       case Bytecodes::_athrow:  // fall through
 306       case Bytecodes::_ret:     // fall through
 307       case Bytecodes::_ireturn: // fall through
 308       case Bytecodes::_lreturn: // fall through
 309       case Bytecodes::_freturn: // fall through
 310       case Bytecodes::_dreturn: // fall through
 311       case Bytecodes::_areturn: // fall through
 312       case Bytecodes::_return:
 313         current = nullptr;
 314         break;
 315 
 316       case Bytecodes::_ifeq:      // fall through
 317       case Bytecodes::_ifne:      // fall through
 318       case Bytecodes::_iflt:      // fall through
 319       case Bytecodes::_ifge:      // fall through
 320       case Bytecodes::_ifgt:      // fall through
 321       case Bytecodes::_ifle:      // fall through
 322       case Bytecodes::_if_icmpeq: // fall through
 323       case Bytecodes::_if_icmpne: // fall through
 324       case Bytecodes::_if_icmplt: // fall through
 325       case Bytecodes::_if_icmpge: // fall through
 326       case Bytecodes::_if_icmpgt: // fall through
 327       case Bytecodes::_if_icmple: // fall through
 328       case Bytecodes::_if_acmpeq: // fall through
 329       case Bytecodes::_if_acmpne: // fall through
 330       case Bytecodes::_ifnull:    // fall through
 331       case Bytecodes::_ifnonnull:
 332         if (s.next_bci() < end_bci) {
 333           make_block_at(s.next_bci(), current);
 334         }
 335         make_block_at(s.get_dest(), current);
 336         current = nullptr;
 337         break;
 338 
 339       case Bytecodes::_goto:
 340         make_block_at(s.get_dest(), current);
 341         current = nullptr;
 342         break;
 343 
 344       case Bytecodes::_goto_w:
 345         make_block_at(s.get_far_dest(), current);
 346         current = nullptr;
 347         break;
 348 
 349       case Bytecodes::_jsr:
 350         handle_jsr(current, s.get_dest(), s.next_bci());
 351         current = nullptr;
 352         break;
 353 
 354       case Bytecodes::_jsr_w:
 355         handle_jsr(current, s.get_far_dest(), s.next_bci());
 356         current = nullptr;
 357         break;
 358 
 359       case Bytecodes::_tableswitch: {
 360         // set block for each case
 361         Bytecode_tableswitch sw(&s);
 362         int l = sw.length();
 363         for (int i = 0; i < l; i++) {
 364           make_block_at(cur_bci + sw.dest_offset_at(i), current);
 365         }
 366         make_block_at(cur_bci + sw.default_offset(), current);
 367         current = nullptr;
 368         break;
 369       }
 370 
 371       case Bytecodes::_lookupswitch: {
 372         // set block for each case
 373         Bytecode_lookupswitch sw(&s);
 374         int l = sw.number_of_pairs();
 375         for (int i = 0; i < l; i++) {
 376           make_block_at(cur_bci + sw.pair_at(i).offset(), current);
 377         }
 378         make_block_at(cur_bci + sw.default_offset(), current);
 379         current = nullptr;
 380         break;
 381       }
 382 
 383       default:
 384         break;
 385     }
 386   }
 387 }
 388 
 389 
 390 void BlockListBuilder::mark_loops() {
 391   ResourceMark rm;
 392 
 393   const int number_of_blocks = _blocks.length();
 394   _active.initialize(number_of_blocks);
 395   _visited.initialize(number_of_blocks);
 396   _loop_map = GrowableArray<ResourceBitMap>(number_of_blocks, number_of_blocks, ResourceBitMap());
 397   for (int i = 0; i < number_of_blocks; i++) {
 398     _loop_map.at(i).initialize(number_of_blocks);
 399   }
 400   _next_loop_index = 0;
 401   _next_block_number = _blocks.length();
 402 
 403   // The loop detection algorithm works as follows:
 404   // - We maintain the _loop_map, where for each block we have a bitmap indicating which loops contain this block.
 405   // - The CFG is recursively traversed (depth-first) and if we detect a loop, we assign the loop a unique number that is stored
 406   // in the bitmap associated with the loop header block. Until we return back through that loop header the bitmap contains
 407   // only a single bit corresponding to the loop number.
 408   // -  The bit is then propagated for all the blocks in the loop after we exit them (post-order). There could be multiple bits
 409   // of course in case of nested loops.
 410   // -  When we exit the loop header we remove that single bit and assign the real loop state for it.
 411   // -  Now, the tricky part here is how we detect irreducible loops. In the algorithm above the loop state bits
 412   // are propagated to the predecessors. If we encounter an irreducible loop (a loop with multiple heads) we would see
 413   // a node with some loop bit set that would then propagate back and be never cleared because we would
 414   // never go back through the original loop header. Therefore if there are any irreducible loops the bits in the states
 415   // for these loops are going to propagate back to the root.
 416   BlockBegin* start = _bci2block->at(0);
 417   _block_id_start = start->block_id();
 418   BitMap& loop_state = mark_loops(start, false);
 419   if (!loop_state.is_empty()) {
 420     compilation()->set_has_irreducible_loops(true);
 421   }
 422   assert(_next_block_number >= 0, "invalid block numbers");
 423 
 424   // Remove dangling Resource pointers before the ResourceMark goes out-of-scope.
 425   _active.resize(0);
 426   _visited.resize(0);
 427   _loop_map.clear();
 428 }
 429 
 430 void BlockListBuilder::make_loop_header(BlockBegin* block) {
 431   int block_id = block->block_id();
 432   int block_bit = bit_number(block_id);
 433   if (block->is_set(BlockBegin::exception_entry_flag)) {
 434     // exception edges may look like loops but don't mark them as such
 435     // since it screws up block ordering.
 436     return;
 437   }
 438   if (!block->is_set(BlockBegin::parser_loop_header_flag)) {
 439     block->set(BlockBegin::parser_loop_header_flag);
 440 
 441     assert(_loop_map.at(block_bit).is_empty(), "must not be set yet");
 442     assert(0 <= _next_loop_index && _next_loop_index < _loop_map.length(), "_next_loop_index is too large");
 443     _loop_map.at(block_bit).set_bit(_next_loop_index++);
 444   } else {
 445     // block already marked as loop header
 446     assert(_loop_map.at(block_bit).count_one_bits() == 1, "exactly one bit must be set");
 447   }
 448 }
 449 
 450 BitMap& BlockListBuilder::mark_loops(BlockBegin* block, bool in_subroutine) {
 451   int block_id = block->block_id();
 452   int block_bit = bit_number(block_id);
 453   if (_visited.at(block_bit)) {
 454     if (_active.at(block_bit)) {
 455       // reached block via backward branch
 456       make_loop_header(block);
 457     }
 458     // return cached loop information for this block
 459     return _loop_map.at(block_bit);
 460   }
 461 
 462   if (block->is_set(BlockBegin::subroutine_entry_flag)) {
 463     in_subroutine = true;
 464   }
 465 
 466   // set active and visited bits before successors are processed
 467   _visited.set_bit(block_bit);
 468   _active.set_bit(block_bit);
 469 
 470   ResourceMark rm;
 471   ResourceBitMap loop_state(_loop_map.length());
 472   for (int i = number_of_successors(block) - 1; i >= 0; i--) {
 473     BlockBegin* sux = successor_at(block, i);
 474     // recursively process all successors
 475     loop_state.set_union(mark_loops(sux, in_subroutine));
 476   }
 477 
 478   // clear active-bit after all successors are processed
 479   _active.clear_bit(block_bit);
 480 
 481   // reverse-post-order numbering of all blocks
 482   block->set_depth_first_number(_next_block_number);
 483   _next_block_number--;
 484 
 485   if (!loop_state.is_empty() || in_subroutine ) {
 486     // block is contained at least in one loop, so phi functions are necessary
 487     // phi functions are also necessary for all locals stored in a subroutine
 488     scope()->requires_phi_function().set_union(block->stores_to_locals());
 489   }
 490 
 491   if (block->is_set(BlockBegin::parser_loop_header_flag)) {
 492     BitMap& header_loop_state = _loop_map.at(block_bit);
 493     assert(header_loop_state.count_one_bits() == 1, "exactly one bit must be set");
 494     // remove the bit with the loop number for the state (header is outside of the loop)
 495     loop_state.set_difference(header_loop_state);
 496   }
 497 
 498   // cache and return loop information for this block
 499   _loop_map.at(block_bit).set_from(loop_state);
 500   return _loop_map.at(block_bit);
 501 }
 502 
 503 inline int BlockListBuilder::number_of_successors(BlockBegin* block)
 504 {
 505   assert(_bci2block_successors.length() > block->bci(), "sux must exist");
 506   return _bci2block_successors.at(block->bci()).length();
 507 }
 508 
 509 inline BlockBegin* BlockListBuilder::successor_at(BlockBegin* block, int i)
 510 {
 511   assert(_bci2block_successors.length() > block->bci(), "sux must exist");
 512   return _bci2block_successors.at(block->bci()).at(i);
 513 }
 514 
 515 inline void BlockListBuilder::add_successor(BlockBegin* block, BlockBegin* sux)
 516 {
 517   assert(_bci2block_successors.length() > block->bci(), "sux must exist");
 518   _bci2block_successors.at(block->bci()).append(sux);
 519 }
 520 
 521 inline bool BlockListBuilder::is_successor(BlockBegin* block, BlockBegin* sux) {
 522   assert(_bci2block_successors.length() > block->bci(), "sux must exist");
 523   return _bci2block_successors.at(block->bci()).contains(sux);
 524 }
 525 
 526 #ifndef PRODUCT
 527 
 528 static int compare_depth_first(BlockBegin** a, BlockBegin** b) {
 529   return (*a)->depth_first_number() - (*b)->depth_first_number();
 530 }
 531 
 532 void BlockListBuilder::print() {
 533   tty->print("----- initial block list of BlockListBuilder for method ");
 534   method()->print_short_name();
 535   tty->cr();
 536 
 537   // better readability if blocks are sorted in processing order
 538   _blocks.sort(compare_depth_first);
 539 
 540   for (int i = 0; i < _blocks.length(); i++) {
 541     BlockBegin* cur = _blocks.at(i);
 542     tty->print("%4d: B%-4d bci: %-4d  preds: %-4d ", cur->depth_first_number(), cur->block_id(), cur->bci(), cur->total_preds());
 543 
 544     tty->print(cur->is_set(BlockBegin::std_entry_flag)               ? " std" : "    ");
 545     tty->print(cur->is_set(BlockBegin::osr_entry_flag)               ? " osr" : "    ");
 546     tty->print(cur->is_set(BlockBegin::exception_entry_flag)         ? " ex" : "   ");
 547     tty->print(cur->is_set(BlockBegin::subroutine_entry_flag)        ? " sr" : "   ");
 548     tty->print(cur->is_set(BlockBegin::parser_loop_header_flag)      ? " lh" : "   ");
 549 
 550     if (number_of_successors(cur) > 0) {
 551       tty->print("    sux: ");
 552       for (int j = 0; j < number_of_successors(cur); j++) {
 553         BlockBegin* sux = successor_at(cur, j);
 554         tty->print("B%d ", sux->block_id());
 555       }
 556     }
 557     tty->cr();
 558   }
 559 }
 560 
 561 #endif
 562 
 563 
 564 // A simple growable array of Values indexed by ciFields
 565 class FieldBuffer: public CompilationResourceObj {
 566  private:
 567   GrowableArray<Value> _values;
 568 
 569  public:
 570   FieldBuffer() {}
 571 
 572   void kill() {
 573     _values.trunc_to(0);
 574   }
 575 
 576   Value at(ciField* field) {
 577     assert(field->holder()->is_loaded(), "must be a loaded field");
 578     int offset = field->offset_in_bytes();
 579     if (offset < _values.length()) {
 580       return _values.at(offset);
 581     } else {
 582       return nullptr;
 583     }
 584   }
 585 
 586   void at_put(ciField* field, Value value) {
 587     assert(field->holder()->is_loaded(), "must be a loaded field");
 588     int offset = field->offset_in_bytes();
 589     _values.at_put_grow(offset, value, nullptr);
 590   }
 591 
 592 };
 593 
 594 
 595 // MemoryBuffer is fairly simple model of the current state of memory.
 596 // It partitions memory into several pieces.  The first piece is
 597 // generic memory where little is known about the owner of the memory.
 598 // This is conceptually represented by the tuple <O, F, V> which says
 599 // that the field F of object O has value V.  This is flattened so
 600 // that F is represented by the offset of the field and the parallel
 601 // arrays _objects and _values are used for O and V.  Loads of O.F can
 602 // simply use V.  Newly allocated objects are kept in a separate list
 603 // along with a parallel array for each object which represents the
 604 // current value of its fields.  Stores of the default value to fields
 605 // which have never been stored to before are eliminated since they
 606 // are redundant.  Once newly allocated objects are stored into
 607 // another object or they are passed out of the current compile they
 608 // are treated like generic memory.
 609 
 610 class MemoryBuffer: public CompilationResourceObj {
 611  private:
 612   FieldBuffer                 _values;
 613   GrowableArray<Value>        _objects;
 614   GrowableArray<Value>        _newobjects;
 615   GrowableArray<FieldBuffer*> _fields;
 616 
 617  public:
 618   MemoryBuffer() {}
 619 
 620   StoreField* store(StoreField* st) {
 621     if (!EliminateFieldAccess) {
 622       return st;
 623     }
 624 
 625     Value object = st->obj();
 626     Value value = st->value();
 627     ciField* field = st->field();
 628     if (field->holder()->is_loaded()) {
 629       int offset = field->offset_in_bytes();
 630       int index = _newobjects.find(object);
 631       if (index != -1) {
 632         // newly allocated object with no other stores performed on this field
 633         FieldBuffer* buf = _fields.at(index);
 634         if (buf->at(field) == nullptr && is_default_value(value)) {
 635 #ifndef PRODUCT
 636           if (PrintIRDuringConstruction && Verbose) {
 637             tty->print_cr("Eliminated store for object %d:", index);
 638             st->print_line();
 639           }
 640 #endif
 641           return nullptr;
 642         } else {
 643           buf->at_put(field, value);
 644         }
 645       } else {
 646         _objects.at_put_grow(offset, object, nullptr);
 647         _values.at_put(field, value);
 648       }
 649 
 650       store_value(value);
 651     } else {
 652       // if we held onto field names we could alias based on names but
 653       // we don't know what's being stored to so kill it all.
 654       kill();
 655     }
 656     return st;
 657   }
 658 
 659 
 660   // return true if this value correspond to the default value of a field.
 661   bool is_default_value(Value value) {
 662     Constant* con = value->as_Constant();
 663     if (con) {
 664       switch (con->type()->tag()) {
 665         case intTag:    return con->type()->as_IntConstant()->value() == 0;
 666         case longTag:   return con->type()->as_LongConstant()->value() == 0;
 667         case floatTag:  return jint_cast(con->type()->as_FloatConstant()->value()) == 0;
 668         case doubleTag: return jlong_cast(con->type()->as_DoubleConstant()->value()) == jlong_cast(0);
 669         case objectTag: return con->type() == objectNull;
 670         default:  ShouldNotReachHere();
 671       }
 672     }
 673     return false;
 674   }
 675 
 676 
 677   // return either the actual value of a load or the load itself
 678   Value load(LoadField* load) {
 679     if (!EliminateFieldAccess) {
 680       return load;
 681     }
 682 
 683     if (strict_fp_requires_explicit_rounding && load->type()->is_float_kind()) {
 684 #ifdef IA32
 685       if (UseSSE < 2) {
 686         // can't skip load since value might get rounded as a side effect
 687         return load;
 688       }
 689 #else
 690       Unimplemented();
 691 #endif // IA32
 692     }
 693 
 694     ciField* field = load->field();
 695     Value object   = load->obj();
 696     if (field->holder()->is_loaded() && !field->is_volatile()) {
 697       int offset = field->offset_in_bytes();
 698       Value result = nullptr;
 699       int index = _newobjects.find(object);
 700       if (index != -1) {
 701         result = _fields.at(index)->at(field);
 702       } else if (_objects.at_grow(offset, nullptr) == object) {
 703         result = _values.at(field);
 704       }
 705       if (result != nullptr) {
 706 #ifndef PRODUCT
 707         if (PrintIRDuringConstruction && Verbose) {
 708           tty->print_cr("Eliminated load: ");
 709           load->print_line();
 710         }
 711 #endif
 712         assert(result->type()->tag() == load->type()->tag(), "wrong types");
 713         return result;
 714       }
 715     }
 716     return load;
 717   }
 718 
 719   // Record this newly allocated object
 720   void new_instance(NewInstance* object) {
 721     int index = _newobjects.length();
 722     _newobjects.append(object);
 723     if (_fields.at_grow(index, nullptr) == nullptr) {
 724       _fields.at_put(index, new FieldBuffer());
 725     } else {
 726       _fields.at(index)->kill();
 727     }
 728   }
 729 
 730   void store_value(Value value) {
 731     int index = _newobjects.find(value);
 732     if (index != -1) {
 733       // stored a newly allocated object into another object.
 734       // Assume we've lost track of it as separate slice of memory.
 735       // We could do better by keeping track of whether individual
 736       // fields could alias each other.
 737       _newobjects.remove_at(index);
 738       // pull out the field info and store it at the end up the list
 739       // of field info list to be reused later.
 740       _fields.append(_fields.at(index));
 741       _fields.remove_at(index);
 742     }
 743   }
 744 
 745   void kill() {
 746     _newobjects.trunc_to(0);
 747     _objects.trunc_to(0);
 748     _values.kill();
 749   }
 750 };
 751 
 752 
 753 // Implementation of GraphBuilder's ScopeData
 754 
 755 GraphBuilder::ScopeData::ScopeData(ScopeData* parent)
 756   : _parent(parent)
 757   , _bci2block(nullptr)
 758   , _scope(nullptr)
 759   , _has_handler(false)
 760   , _stream(nullptr)
 761   , _work_list(nullptr)
 762   , _caller_stack_size(-1)
 763   , _continuation(nullptr)
 764   , _parsing_jsr(false)
 765   , _jsr_xhandlers(nullptr)
 766   , _num_returns(0)
 767   , _cleanup_block(nullptr)
 768   , _cleanup_return_prev(nullptr)
 769   , _cleanup_state(nullptr)
 770   , _ignore_return(false)
 771 {
 772   if (parent != nullptr) {
 773     _max_inline_size = (intx) ((float) NestedInliningSizeRatio * (float) parent->max_inline_size() / 100.0f);
 774   } else {
 775     _max_inline_size = C1MaxInlineSize;
 776   }
 777   if (_max_inline_size < C1MaxTrivialSize) {
 778     _max_inline_size = C1MaxTrivialSize;
 779   }
 780 }
 781 
 782 
 783 void GraphBuilder::kill_all() {
 784   if (UseLocalValueNumbering) {
 785     vmap()->kill_all();
 786   }
 787   _memory->kill();
 788 }
 789 
 790 
 791 BlockBegin* GraphBuilder::ScopeData::block_at(int bci) {
 792   if (parsing_jsr()) {
 793     // It is necessary to clone all blocks associated with a
 794     // subroutine, including those for exception handlers in the scope
 795     // of the method containing the jsr (because those exception
 796     // handlers may contain ret instructions in some cases).
 797     BlockBegin* block = bci2block()->at(bci);
 798     if (block != nullptr && block == parent()->bci2block()->at(bci)) {
 799       BlockBegin* new_block = new BlockBegin(block->bci());
 800       if (PrintInitialBlockList) {
 801         tty->print_cr("CFG: cloned block %d (bci %d) as block %d for jsr",
 802                       block->block_id(), block->bci(), new_block->block_id());
 803       }
 804       // copy data from cloned blocked
 805       new_block->set_depth_first_number(block->depth_first_number());
 806       if (block->is_set(BlockBegin::parser_loop_header_flag)) new_block->set(BlockBegin::parser_loop_header_flag);
 807       // Preserve certain flags for assertion checking
 808       if (block->is_set(BlockBegin::subroutine_entry_flag)) new_block->set(BlockBegin::subroutine_entry_flag);
 809       if (block->is_set(BlockBegin::exception_entry_flag))  new_block->set(BlockBegin::exception_entry_flag);
 810 
 811       // copy was_visited_flag to allow early detection of bailouts
 812       // if a block that is used in a jsr has already been visited before,
 813       // it is shared between the normal control flow and a subroutine
 814       // BlockBegin::try_merge returns false when the flag is set, this leads
 815       // to a compilation bailout
 816       if (block->is_set(BlockBegin::was_visited_flag))  new_block->set(BlockBegin::was_visited_flag);
 817 
 818       bci2block()->at_put(bci, new_block);
 819       block = new_block;
 820     }
 821     return block;
 822   } else {
 823     return bci2block()->at(bci);
 824   }
 825 }
 826 
 827 
 828 XHandlers* GraphBuilder::ScopeData::xhandlers() const {
 829   if (_jsr_xhandlers == nullptr) {
 830     assert(!parsing_jsr(), "");
 831     return scope()->xhandlers();
 832   }
 833   assert(parsing_jsr(), "");
 834   return _jsr_xhandlers;
 835 }
 836 
 837 
 838 void GraphBuilder::ScopeData::set_scope(IRScope* scope) {
 839   _scope = scope;
 840   bool parent_has_handler = false;
 841   if (parent() != nullptr) {
 842     parent_has_handler = parent()->has_handler();
 843   }
 844   _has_handler = parent_has_handler || scope->xhandlers()->has_handlers();
 845 }
 846 
 847 
 848 void GraphBuilder::ScopeData::set_inline_cleanup_info(BlockBegin* block,
 849                                                       Instruction* return_prev,
 850                                                       ValueStack* return_state) {
 851   _cleanup_block       = block;
 852   _cleanup_return_prev = return_prev;
 853   _cleanup_state       = return_state;
 854 }
 855 
 856 
 857 void GraphBuilder::ScopeData::add_to_work_list(BlockBegin* block) {
 858   if (_work_list == nullptr) {
 859     _work_list = new BlockList();
 860   }
 861 
 862   if (!block->is_set(BlockBegin::is_on_work_list_flag)) {
 863     // Do not start parsing the continuation block while in a
 864     // sub-scope
 865     if (parsing_jsr()) {
 866       if (block == jsr_continuation()) {
 867         return;
 868       }
 869     } else {
 870       if (block == continuation()) {
 871         return;
 872       }
 873     }
 874     block->set(BlockBegin::is_on_work_list_flag);
 875     _work_list->push(block);
 876 
 877     sort_top_into_worklist(_work_list, block);
 878   }
 879 }
 880 
 881 
 882 void GraphBuilder::sort_top_into_worklist(BlockList* worklist, BlockBegin* top) {
 883   assert(worklist->top() == top, "");
 884   // sort block descending into work list
 885   const int dfn = top->depth_first_number();
 886   assert(dfn != -1, "unknown depth first number");
 887   int i = worklist->length()-2;
 888   while (i >= 0) {
 889     BlockBegin* b = worklist->at(i);
 890     if (b->depth_first_number() < dfn) {
 891       worklist->at_put(i+1, b);
 892     } else {
 893       break;
 894     }
 895     i --;
 896   }
 897   if (i >= -1) worklist->at_put(i + 1, top);
 898 }
 899 
 900 
 901 BlockBegin* GraphBuilder::ScopeData::remove_from_work_list() {
 902   if (is_work_list_empty()) {
 903     return nullptr;
 904   }
 905   return _work_list->pop();
 906 }
 907 
 908 
 909 bool GraphBuilder::ScopeData::is_work_list_empty() const {
 910   return (_work_list == nullptr || _work_list->length() == 0);
 911 }
 912 
 913 
 914 void GraphBuilder::ScopeData::setup_jsr_xhandlers() {
 915   assert(parsing_jsr(), "");
 916   // clone all the exception handlers from the scope
 917   XHandlers* handlers = new XHandlers(scope()->xhandlers());
 918   const int n = handlers->length();
 919   for (int i = 0; i < n; i++) {
 920     // The XHandlers need to be adjusted to dispatch to the cloned
 921     // handler block instead of the default one but the synthetic
 922     // unlocker needs to be handled specially.  The synthetic unlocker
 923     // should be left alone since there can be only one and all code
 924     // should dispatch to the same one.
 925     XHandler* h = handlers->handler_at(i);
 926     assert(h->handler_bci() != SynchronizationEntryBCI, "must be real");
 927     h->set_entry_block(block_at(h->handler_bci()));
 928   }
 929   _jsr_xhandlers = handlers;
 930 }
 931 
 932 
 933 int GraphBuilder::ScopeData::num_returns() {
 934   if (parsing_jsr()) {
 935     return parent()->num_returns();
 936   }
 937   return _num_returns;
 938 }
 939 
 940 
 941 void GraphBuilder::ScopeData::incr_num_returns() {
 942   if (parsing_jsr()) {
 943     parent()->incr_num_returns();
 944   } else {
 945     ++_num_returns;
 946   }
 947 }
 948 
 949 
 950 // Implementation of GraphBuilder
 951 
 952 #define INLINE_BAILOUT(msg)        { inline_bailout(msg); return false; }
 953 
 954 
 955 void GraphBuilder::load_constant() {
 956   ciConstant con = stream()->get_constant();
 957   if (con.is_valid()) {
 958     ValueType* t = illegalType;
 959     ValueStack* patch_state = nullptr;
 960     switch (con.basic_type()) {
 961       case T_BOOLEAN: t = new IntConstant   (con.as_boolean()); break;
 962       case T_BYTE   : t = new IntConstant   (con.as_byte   ()); break;
 963       case T_CHAR   : t = new IntConstant   (con.as_char   ()); break;
 964       case T_SHORT  : t = new IntConstant   (con.as_short  ()); break;
 965       case T_INT    : t = new IntConstant   (con.as_int    ()); break;
 966       case T_LONG   : t = new LongConstant  (con.as_long   ()); break;
 967       case T_FLOAT  : t = new FloatConstant (con.as_float  ()); break;
 968       case T_DOUBLE : t = new DoubleConstant(con.as_double ()); break;
 969       case T_ARRAY  : // fall-through
 970       case T_OBJECT : {
 971         ciObject* obj = con.as_object();
 972         if (!obj->is_loaded() || (PatchALot && !stream()->is_string_constant())) {
 973           // A Class, MethodType, MethodHandle, Dynamic, or String.
 974           patch_state = copy_state_before();
 975           t = new ObjectConstant(obj);
 976         } else {
 977           // Might be a Class, MethodType, MethodHandle, or Dynamic constant
 978           // result, which might turn out to be an array.
 979           if (obj->is_null_object()) {
 980             t = objectNull;
 981           } else if (obj->is_array()) {
 982             t = new ArrayConstant(obj->as_array());
 983           } else {
 984             t = new InstanceConstant(obj->as_instance());
 985           }
 986         }
 987         break;
 988       }
 989       default: ShouldNotReachHere();
 990     }
 991     Value x;
 992     if (patch_state != nullptr) {
 993       // Arbitrary memory effects from running BSM or class loading (using custom loader) during linkage.
 994       bool kills_memory = stream()->is_dynamic_constant() ||
 995                           (!stream()->is_string_constant() && !method()->holder()->has_trusted_loader());
 996       x = new Constant(t, patch_state, kills_memory);
 997     } else {
 998       x = new Constant(t);
 999     }
1000 
1001     // Unbox the value at runtime, if needed.
1002     // ConstantDynamic entry can be of a primitive type, but it is cached in boxed form.
1003     if (patch_state != nullptr) {
1004       int cp_index = stream()->get_constant_pool_index();
1005       BasicType type = stream()->get_basic_type_for_constant_at(cp_index);
1006       if (is_java_primitive(type)) {
1007         ciInstanceKlass* box_klass = ciEnv::current()->get_box_klass_for_primitive_type(type);
1008         assert(box_klass->is_loaded(), "sanity");
1009         int offset = java_lang_boxing_object::value_offset(type);
1010         ciField* value_field = box_klass->get_field_by_offset(offset, false /*is_static*/);
1011         x = new LoadField(append(x), offset, value_field, false /*is_static*/, patch_state, false /*needs_patching*/);
1012         t = as_ValueType(type);
1013       } else {
1014         assert(is_reference_type(type), "not a reference: %s", type2name(type));
1015       }
1016     }
1017 
1018     push(t, append(x));
1019   } else {
1020     BAILOUT("could not resolve a constant");
1021   }
1022 }
1023 
1024 
1025 void GraphBuilder::load_local(ValueType* type, int index) {
1026   Value x = state()->local_at(index);
1027   assert(x != nullptr && !x->type()->is_illegal(), "access of illegal local variable");
1028   push(type, x);
1029 }
1030 
1031 
1032 void GraphBuilder::store_local(ValueType* type, int index) {
1033   Value x = pop(type);
1034   store_local(state(), x, index);
1035 }
1036 
1037 
1038 void GraphBuilder::store_local(ValueStack* state, Value x, int index) {
1039   if (parsing_jsr()) {
1040     // We need to do additional tracking of the location of the return
1041     // address for jsrs since we don't handle arbitrary jsr/ret
1042     // constructs. Here we are figuring out in which circumstances we
1043     // need to bail out.
1044     if (x->type()->is_address()) {
1045       scope_data()->set_jsr_return_address_local(index);
1046 
1047       // Also check parent jsrs (if any) at this time to see whether
1048       // they are using this local. We don't handle skipping over a
1049       // ret.
1050       for (ScopeData* cur_scope_data = scope_data()->parent();
1051            cur_scope_data != nullptr && cur_scope_data->parsing_jsr() && cur_scope_data->scope() == scope();
1052            cur_scope_data = cur_scope_data->parent()) {
1053         if (cur_scope_data->jsr_return_address_local() == index) {
1054           BAILOUT("subroutine overwrites return address from previous subroutine");
1055         }
1056       }
1057     } else if (index == scope_data()->jsr_return_address_local()) {
1058       scope_data()->set_jsr_return_address_local(-1);
1059     }
1060   }
1061 
1062   state->store_local(index, round_fp(x));
1063 }
1064 
1065 
1066 void GraphBuilder::load_indexed(BasicType type) {
1067   // In case of in block code motion in range check elimination
1068   ValueStack* state_before = nullptr;
1069   int array_idx = state()->stack_size() - 2;
1070   if (type == T_OBJECT && state()->stack_at(array_idx)->maybe_flat_array()) {
1071     // Save the entire state and re-execute on deopt when accessing flat arrays
1072     state_before = copy_state_before();
1073     state_before->set_should_reexecute(true);
1074   } else {
1075     state_before = copy_state_indexed_access();
1076   }
1077   compilation()->set_has_access_indexed(true);
1078   Value index = ipop();
1079   Value array = apop();
1080   Value length = nullptr;
1081   if (CSEArrayLength ||
1082       (array->as_Constant() != nullptr) ||
1083       (array->as_AccessField() && array->as_AccessField()->field()->is_constant()) ||
1084       (array->as_NewArray() && array->as_NewArray()->length() && array->as_NewArray()->length()->type()->is_constant()) ||
1085       (array->as_NewMultiArray() && array->as_NewMultiArray()->dims()->at(0)->type()->is_constant())) {
1086     length = append(new ArrayLength(array, state_before));
1087   }
1088 
1089   bool need_membar = false;
1090   LoadIndexed* load_indexed = nullptr;
1091   Instruction* result = nullptr;
1092   if (array->is_loaded_flat_array()) {
1093     ciType* array_type = array->declared_type();
1094     ciInlineKlass* elem_klass = array_type->as_flat_array_klass()->element_klass()->as_inline_klass();
1095 
1096     bool can_delay_access = false;
1097     ciBytecodeStream s(method());
1098     s.force_bci(bci());
1099     s.next();
1100     if (s.cur_bc() == Bytecodes::_getfield) {
1101       bool will_link;
1102       ciField* next_field = s.get_field(will_link);
1103       bool next_needs_patching = !next_field->holder()->is_initialized() ||
1104                                  !next_field->will_link(method(), Bytecodes::_getfield) ||
1105                                  PatchALot;
1106       can_delay_access = C1UseDelayedFlattenedFieldReads && !next_needs_patching;
1107     }
1108     if (can_delay_access) {
1109       // potentially optimizable array access, storing information for delayed decision
1110       LoadIndexed* li = new LoadIndexed(array, index, length, type, state_before);
1111       DelayedLoadIndexed* dli = new DelayedLoadIndexed(li, state_before);
1112       li->set_delayed(dli);
1113       set_pending_load_indexed(dli);
1114       return; // Nothing else to do for now
1115     } else {
1116       if (elem_klass->is_empty()) {
1117         // No need to create a new instance, the default instance will be used instead
1118         load_indexed = new LoadIndexed(array, index, length, type, state_before);
1119         apush(append(load_indexed));
1120       } else {
1121         NewInstance* new_instance = new NewInstance(elem_klass, state_before, false, true);
1122         _memory->new_instance(new_instance);
1123         apush(append_split(new_instance));
1124         load_indexed = new LoadIndexed(array, index, length, type, state_before);
1125         load_indexed->set_vt(new_instance);
1126         // The LoadIndexed node will initialise this instance by copying from
1127         // the flat field.  Ensure these stores are visible before any
1128         // subsequent store that publishes this reference.
1129         need_membar = true;
1130       }
1131     }
1132   } else {
1133     load_indexed = new LoadIndexed(array, index, length, type, state_before);
1134     if (profile_array_accesses() && is_reference_type(type)) {
1135       compilation()->set_would_profile(true);
1136       load_indexed->set_should_profile(true);
1137       load_indexed->set_profiled_method(method());
1138       load_indexed->set_profiled_bci(bci());
1139     }
1140   }
1141   result = append(load_indexed);
1142   if (need_membar) {
1143     append(new MemBar(lir_membar_storestore));
1144   }
1145   assert(!load_indexed->should_profile() || load_indexed == result, "should not be optimized out");
1146   if (!array->is_loaded_flat_array()) {
1147     push(as_ValueType(type), result);
1148   }
1149 }
1150 
1151 
1152 void GraphBuilder::store_indexed(BasicType type) {
1153   // In case of in block code motion in range check elimination
1154   ValueStack* state_before = nullptr;
1155   int array_idx = state()->stack_size() - 3;
1156   if (type == T_OBJECT && state()->stack_at(array_idx)->maybe_flat_array()) {
1157     // Save the entire state and re-execute on deopt when accessing flat arrays
1158     state_before = copy_state_before();
1159     state_before->set_should_reexecute(true);
1160   } else {
1161     state_before = copy_state_indexed_access();
1162   }
1163   compilation()->set_has_access_indexed(true);
1164   Value value = pop(as_ValueType(type));
1165   Value index = ipop();
1166   Value array = apop();
1167   Value length = nullptr;
1168   if (CSEArrayLength ||
1169       (array->as_Constant() != nullptr) ||
1170       (array->as_AccessField() && array->as_AccessField()->field()->is_constant()) ||
1171       (array->as_NewArray() && array->as_NewArray()->length() && array->as_NewArray()->length()->type()->is_constant()) ||
1172       (array->as_NewMultiArray() && array->as_NewMultiArray()->dims()->at(0)->type()->is_constant())) {
1173     length = append(new ArrayLength(array, state_before));
1174   }
1175   ciType* array_type = array->declared_type();
1176   bool check_boolean = false;
1177   if (array_type != nullptr) {
1178     if (array_type->is_loaded() &&
1179       array_type->as_array_klass()->element_type()->basic_type() == T_BOOLEAN) {
1180       assert(type == T_BYTE, "boolean store uses bastore");
1181       Value mask = append(new Constant(new IntConstant(1)));
1182       value = append(new LogicOp(Bytecodes::_iand, value, mask));
1183     }
1184   } else if (type == T_BYTE) {
1185     check_boolean = true;
1186   }
1187 
1188   StoreIndexed* store_indexed = new StoreIndexed(array, index, length, type, value, state_before, check_boolean);
1189   if (profile_array_accesses() && is_reference_type(type) && !array->is_loaded_flat_array()) {
1190     compilation()->set_would_profile(true);
1191     store_indexed->set_should_profile(true);
1192     store_indexed->set_profiled_method(method());
1193     store_indexed->set_profiled_bci(bci());
1194   }
1195   Instruction* result = append(store_indexed);
1196   assert(!store_indexed->should_profile() || store_indexed == result, "should not be optimized out");
1197   _memory->store_value(value);
1198 }
1199 
1200 void GraphBuilder::stack_op(Bytecodes::Code code) {
1201   switch (code) {
1202     case Bytecodes::_pop:
1203       { Value w = state()->raw_pop();
1204       }
1205       break;
1206     case Bytecodes::_pop2:
1207       { Value w1 = state()->raw_pop();
1208         Value w2 = state()->raw_pop();
1209       }
1210       break;
1211     case Bytecodes::_dup:
1212       { Value w = state()->raw_pop();
1213         state()->raw_push(w);
1214         state()->raw_push(w);
1215       }
1216       break;
1217     case Bytecodes::_dup_x1:
1218       { Value w1 = state()->raw_pop();
1219         Value w2 = state()->raw_pop();
1220         state()->raw_push(w1);
1221         state()->raw_push(w2);
1222         state()->raw_push(w1);
1223       }
1224       break;
1225     case Bytecodes::_dup_x2:
1226       { Value w1 = state()->raw_pop();
1227         Value w2 = state()->raw_pop();
1228         Value w3 = state()->raw_pop();
1229         state()->raw_push(w1);
1230         state()->raw_push(w3);
1231         state()->raw_push(w2);
1232         state()->raw_push(w1);
1233       }
1234       break;
1235     case Bytecodes::_dup2:
1236       { Value w1 = state()->raw_pop();
1237         Value w2 = state()->raw_pop();
1238         state()->raw_push(w2);
1239         state()->raw_push(w1);
1240         state()->raw_push(w2);
1241         state()->raw_push(w1);
1242       }
1243       break;
1244     case Bytecodes::_dup2_x1:
1245       { Value w1 = state()->raw_pop();
1246         Value w2 = state()->raw_pop();
1247         Value w3 = state()->raw_pop();
1248         state()->raw_push(w2);
1249         state()->raw_push(w1);
1250         state()->raw_push(w3);
1251         state()->raw_push(w2);
1252         state()->raw_push(w1);
1253       }
1254       break;
1255     case Bytecodes::_dup2_x2:
1256       { Value w1 = state()->raw_pop();
1257         Value w2 = state()->raw_pop();
1258         Value w3 = state()->raw_pop();
1259         Value w4 = state()->raw_pop();
1260         state()->raw_push(w2);
1261         state()->raw_push(w1);
1262         state()->raw_push(w4);
1263         state()->raw_push(w3);
1264         state()->raw_push(w2);
1265         state()->raw_push(w1);
1266       }
1267       break;
1268     case Bytecodes::_swap:
1269       { Value w1 = state()->raw_pop();
1270         Value w2 = state()->raw_pop();
1271         state()->raw_push(w1);
1272         state()->raw_push(w2);
1273       }
1274       break;
1275     default:
1276       ShouldNotReachHere();
1277       break;
1278   }
1279 }
1280 
1281 
1282 void GraphBuilder::arithmetic_op(ValueType* type, Bytecodes::Code code, ValueStack* state_before) {
1283   Value y = pop(type);
1284   Value x = pop(type);
1285   Value res = new ArithmeticOp(code, x, y, state_before);
1286   // Note: currently single-precision floating-point rounding on Intel is handled at the LIRGenerator level
1287   res = append(res);
1288   res = round_fp(res);
1289   push(type, res);
1290 }
1291 
1292 
1293 void GraphBuilder::negate_op(ValueType* type) {
1294   push(type, append(new NegateOp(pop(type))));
1295 }
1296 
1297 
1298 void GraphBuilder::shift_op(ValueType* type, Bytecodes::Code code) {
1299   Value s = ipop();
1300   Value x = pop(type);
1301   // try to simplify
1302   // Note: This code should go into the canonicalizer as soon as it can
1303   //       can handle canonicalized forms that contain more than one node.
1304   if (CanonicalizeNodes && code == Bytecodes::_iushr) {
1305     // pattern: x >>> s
1306     IntConstant* s1 = s->type()->as_IntConstant();
1307     if (s1 != nullptr) {
1308       // pattern: x >>> s1, with s1 constant
1309       ShiftOp* l = x->as_ShiftOp();
1310       if (l != nullptr && l->op() == Bytecodes::_ishl) {
1311         // pattern: (a << b) >>> s1
1312         IntConstant* s0 = l->y()->type()->as_IntConstant();
1313         if (s0 != nullptr) {
1314           // pattern: (a << s0) >>> s1
1315           const int s0c = s0->value() & 0x1F; // only the low 5 bits are significant for shifts
1316           const int s1c = s1->value() & 0x1F; // only the low 5 bits are significant for shifts
1317           if (s0c == s1c) {
1318             if (s0c == 0) {
1319               // pattern: (a << 0) >>> 0 => simplify to: a
1320               ipush(l->x());
1321             } else {
1322               // pattern: (a << s0c) >>> s0c => simplify to: a & m, with m constant
1323               assert(0 < s0c && s0c < BitsPerInt, "adjust code below to handle corner cases");
1324               const int m = checked_cast<int>(right_n_bits(BitsPerInt - s0c));
1325               Value s = append(new Constant(new IntConstant(m)));
1326               ipush(append(new LogicOp(Bytecodes::_iand, l->x(), s)));
1327             }
1328             return;
1329           }
1330         }
1331       }
1332     }
1333   }
1334   // could not simplify
1335   push(type, append(new ShiftOp(code, x, s)));
1336 }
1337 
1338 
1339 void GraphBuilder::logic_op(ValueType* type, Bytecodes::Code code) {
1340   Value y = pop(type);
1341   Value x = pop(type);
1342   push(type, append(new LogicOp(code, x, y)));
1343 }
1344 
1345 
1346 void GraphBuilder::compare_op(ValueType* type, Bytecodes::Code code) {
1347   ValueStack* state_before = copy_state_before();
1348   Value y = pop(type);
1349   Value x = pop(type);
1350   ipush(append(new CompareOp(code, x, y, state_before)));
1351 }
1352 
1353 
1354 void GraphBuilder::convert(Bytecodes::Code op, BasicType from, BasicType to) {
1355   push(as_ValueType(to), append(new Convert(op, pop(as_ValueType(from)), as_ValueType(to))));
1356 }
1357 
1358 
1359 void GraphBuilder::increment() {
1360   int index = stream()->get_index();
1361   int delta = stream()->is_wide() ? (signed short)Bytes::get_Java_u2(stream()->cur_bcp() + 4) : (signed char)(stream()->cur_bcp()[2]);
1362   load_local(intType, index);
1363   ipush(append(new Constant(new IntConstant(delta))));
1364   arithmetic_op(intType, Bytecodes::_iadd);
1365   store_local(intType, index);
1366 }
1367 
1368 
1369 void GraphBuilder::_goto(int from_bci, int to_bci) {
1370   Goto *x = new Goto(block_at(to_bci), to_bci <= from_bci);
1371   if (is_profiling()) {
1372     compilation()->set_would_profile(true);
1373     x->set_profiled_bci(bci());
1374     if (profile_branches()) {
1375       x->set_profiled_method(method());
1376       x->set_should_profile(true);
1377     }
1378   }
1379   append(x);
1380 }
1381 
1382 
1383 void GraphBuilder::if_node(Value x, If::Condition cond, Value y, ValueStack* state_before) {
1384   BlockBegin* tsux = block_at(stream()->get_dest());
1385   BlockBegin* fsux = block_at(stream()->next_bci());
1386   bool is_bb = tsux->bci() < stream()->cur_bci() || fsux->bci() < stream()->cur_bci();
1387 
1388   bool subst_check = false;
1389   if (EnableValhalla && (stream()->cur_bc() == Bytecodes::_if_acmpeq || stream()->cur_bc() == Bytecodes::_if_acmpne)) {
1390     ValueType* left_vt = x->type();
1391     ValueType* right_vt = y->type();
1392     if (left_vt->is_object()) {
1393       assert(right_vt->is_object(), "must be");
1394       ciKlass* left_klass = x->as_loaded_klass_or_null();
1395       ciKlass* right_klass = y->as_loaded_klass_or_null();
1396 
1397       if (left_klass == nullptr || right_klass == nullptr) {
1398         // The klass is still unloaded, or came from a Phi node. Go slow case;
1399         subst_check = true;
1400       } else if (left_klass->can_be_inline_klass() || right_klass->can_be_inline_klass()) {
1401         // Either operand may be a value object, but we're not sure. Go slow case;
1402         subst_check = true;
1403       } else {
1404         // No need to do substitutability check
1405       }
1406     }
1407   }
1408   if ((stream()->cur_bc() == Bytecodes::_if_acmpeq || stream()->cur_bc() == Bytecodes::_if_acmpne) &&
1409       is_profiling() && profile_branches()) {
1410     compilation()->set_would_profile(true);
1411     append(new ProfileACmpTypes(method(), bci(), x, y));
1412   }
1413 
1414   // In case of loop invariant code motion or predicate insertion
1415   // before the body of a loop the state is needed
1416   Instruction *i = append(new If(x, cond, false, y, tsux, fsux, (is_bb || compilation()->is_optimistic() || subst_check) ? state_before : nullptr, is_bb, subst_check));
1417 
1418   assert(i->as_Goto() == nullptr ||
1419          (i->as_Goto()->sux_at(0) == tsux  && i->as_Goto()->is_safepoint() == (tsux->bci() < stream()->cur_bci())) ||
1420          (i->as_Goto()->sux_at(0) == fsux  && i->as_Goto()->is_safepoint() == (fsux->bci() < stream()->cur_bci())),
1421          "safepoint state of Goto returned by canonicalizer incorrect");
1422 
1423   if (is_profiling()) {
1424     If* if_node = i->as_If();
1425     if (if_node != nullptr) {
1426       // Note that we'd collect profile data in this method if we wanted it.
1427       compilation()->set_would_profile(true);
1428       // At level 2 we need the proper bci to count backedges
1429       if_node->set_profiled_bci(bci());
1430       if (profile_branches()) {
1431         // Successors can be rotated by the canonicalizer, check for this case.
1432         if_node->set_profiled_method(method());
1433         if_node->set_should_profile(true);
1434         if (if_node->tsux() == fsux) {
1435           if_node->set_swapped(true);
1436         }
1437       }
1438       return;
1439     }
1440 
1441     // Check if this If was reduced to Goto.
1442     Goto *goto_node = i->as_Goto();
1443     if (goto_node != nullptr) {
1444       compilation()->set_would_profile(true);
1445       goto_node->set_profiled_bci(bci());
1446       if (profile_branches()) {
1447         goto_node->set_profiled_method(method());
1448         goto_node->set_should_profile(true);
1449         // Find out which successor is used.
1450         if (goto_node->default_sux() == tsux) {
1451           goto_node->set_direction(Goto::taken);
1452         } else if (goto_node->default_sux() == fsux) {
1453           goto_node->set_direction(Goto::not_taken);
1454         } else {
1455           ShouldNotReachHere();
1456         }
1457       }
1458       return;
1459     }
1460   }
1461 }
1462 
1463 
1464 void GraphBuilder::if_zero(ValueType* type, If::Condition cond) {
1465   Value y = append(new Constant(intZero));
1466   ValueStack* state_before = copy_state_before();
1467   Value x = ipop();
1468   if_node(x, cond, y, state_before);
1469 }
1470 
1471 
1472 void GraphBuilder::if_null(ValueType* type, If::Condition cond) {
1473   Value y = append(new Constant(objectNull));
1474   ValueStack* state_before = copy_state_before();
1475   Value x = apop();
1476   if_node(x, cond, y, state_before);
1477 }
1478 
1479 
1480 void GraphBuilder::if_same(ValueType* type, If::Condition cond) {
1481   ValueStack* state_before = copy_state_before();
1482   Value y = pop(type);
1483   Value x = pop(type);
1484   if_node(x, cond, y, state_before);
1485 }
1486 
1487 
1488 void GraphBuilder::jsr(int dest) {
1489   // We only handle well-formed jsrs (those which are "block-structured").
1490   // If the bytecodes are strange (jumping out of a jsr block) then we
1491   // might end up trying to re-parse a block containing a jsr which
1492   // has already been activated. Watch for this case and bail out.
1493   for (ScopeData* cur_scope_data = scope_data();
1494        cur_scope_data != nullptr && cur_scope_data->parsing_jsr() && cur_scope_data->scope() == scope();
1495        cur_scope_data = cur_scope_data->parent()) {
1496     if (cur_scope_data->jsr_entry_bci() == dest) {
1497       BAILOUT("too-complicated jsr/ret structure");
1498     }
1499   }
1500 
1501   push(addressType, append(new Constant(new AddressConstant(next_bci()))));
1502   if (!try_inline_jsr(dest)) {
1503     return; // bailed out while parsing and inlining subroutine
1504   }
1505 }
1506 
1507 
1508 void GraphBuilder::ret(int local_index) {
1509   if (!parsing_jsr()) BAILOUT("ret encountered while not parsing subroutine");
1510 
1511   if (local_index != scope_data()->jsr_return_address_local()) {
1512     BAILOUT("can not handle complicated jsr/ret constructs");
1513   }
1514 
1515   // Rets simply become (NON-SAFEPOINT) gotos to the jsr continuation
1516   append(new Goto(scope_data()->jsr_continuation(), false));
1517 }
1518 
1519 
1520 void GraphBuilder::table_switch() {
1521   Bytecode_tableswitch sw(stream());
1522   const int l = sw.length();
1523   if (CanonicalizeNodes && l == 1 && compilation()->env()->comp_level() != CompLevel_full_profile) {
1524     // total of 2 successors => use If instead of switch
1525     // Note: This code should go into the canonicalizer as soon as it can
1526     //       can handle canonicalized forms that contain more than one node.
1527     Value key = append(new Constant(new IntConstant(sw.low_key())));
1528     BlockBegin* tsux = block_at(bci() + sw.dest_offset_at(0));
1529     BlockBegin* fsux = block_at(bci() + sw.default_offset());
1530     bool is_bb = tsux->bci() < bci() || fsux->bci() < bci();
1531     // In case of loop invariant code motion or predicate insertion
1532     // before the body of a loop the state is needed
1533     ValueStack* state_before = copy_state_if_bb(is_bb);
1534     append(new If(ipop(), If::eql, true, key, tsux, fsux, state_before, is_bb));
1535   } else {
1536     // collect successors
1537     BlockList* sux = new BlockList(l + 1, nullptr);
1538     int i;
1539     bool has_bb = false;
1540     for (i = 0; i < l; i++) {
1541       sux->at_put(i, block_at(bci() + sw.dest_offset_at(i)));
1542       if (sw.dest_offset_at(i) < 0) has_bb = true;
1543     }
1544     // add default successor
1545     if (sw.default_offset() < 0) has_bb = true;
1546     sux->at_put(i, block_at(bci() + sw.default_offset()));
1547     // In case of loop invariant code motion or predicate insertion
1548     // before the body of a loop the state is needed
1549     ValueStack* state_before = copy_state_if_bb(has_bb);
1550     Instruction* res = append(new TableSwitch(ipop(), sux, sw.low_key(), state_before, has_bb));
1551 #ifdef ASSERT
1552     if (res->as_Goto()) {
1553       for (i = 0; i < l; i++) {
1554         if (sux->at(i) == res->as_Goto()->sux_at(0)) {
1555           assert(res->as_Goto()->is_safepoint() == (sw.dest_offset_at(i) < 0), "safepoint state of Goto returned by canonicalizer incorrect");
1556         }
1557       }
1558     }
1559 #endif
1560   }
1561 }
1562 
1563 
1564 void GraphBuilder::lookup_switch() {
1565   Bytecode_lookupswitch sw(stream());
1566   const int l = sw.number_of_pairs();
1567   if (CanonicalizeNodes && l == 1 && compilation()->env()->comp_level() != CompLevel_full_profile) {
1568     // total of 2 successors => use If instead of switch
1569     // Note: This code should go into the canonicalizer as soon as it can
1570     //       can handle canonicalized forms that contain more than one node.
1571     // simplify to If
1572     LookupswitchPair pair = sw.pair_at(0);
1573     Value key = append(new Constant(new IntConstant(pair.match())));
1574     BlockBegin* tsux = block_at(bci() + pair.offset());
1575     BlockBegin* fsux = block_at(bci() + sw.default_offset());
1576     bool is_bb = tsux->bci() < bci() || fsux->bci() < bci();
1577     // In case of loop invariant code motion or predicate insertion
1578     // before the body of a loop the state is needed
1579     ValueStack* state_before = copy_state_if_bb(is_bb);;
1580     append(new If(ipop(), If::eql, true, key, tsux, fsux, state_before, is_bb));
1581   } else {
1582     // collect successors & keys
1583     BlockList* sux = new BlockList(l + 1, nullptr);
1584     intArray* keys = new intArray(l, l, 0);
1585     int i;
1586     bool has_bb = false;
1587     for (i = 0; i < l; i++) {
1588       LookupswitchPair pair = sw.pair_at(i);
1589       if (pair.offset() < 0) has_bb = true;
1590       sux->at_put(i, block_at(bci() + pair.offset()));
1591       keys->at_put(i, pair.match());
1592     }
1593     // add default successor
1594     if (sw.default_offset() < 0) has_bb = true;
1595     sux->at_put(i, block_at(bci() + sw.default_offset()));
1596     // In case of loop invariant code motion or predicate insertion
1597     // before the body of a loop the state is needed
1598     ValueStack* state_before = copy_state_if_bb(has_bb);
1599     Instruction* res = append(new LookupSwitch(ipop(), sux, keys, state_before, has_bb));
1600 #ifdef ASSERT
1601     if (res->as_Goto()) {
1602       for (i = 0; i < l; i++) {
1603         if (sux->at(i) == res->as_Goto()->sux_at(0)) {
1604           assert(res->as_Goto()->is_safepoint() == (sw.pair_at(i).offset() < 0), "safepoint state of Goto returned by canonicalizer incorrect");
1605         }
1606       }
1607     }
1608 #endif
1609   }
1610 }
1611 
1612 void GraphBuilder::call_register_finalizer() {
1613   // If the receiver requires finalization then emit code to perform
1614   // the registration on return.
1615 
1616   // Gather some type information about the receiver
1617   Value receiver = state()->local_at(0);
1618   assert(receiver != nullptr, "must have a receiver");
1619   ciType* declared_type = receiver->declared_type();
1620   ciType* exact_type = receiver->exact_type();
1621   if (exact_type == nullptr &&
1622       receiver->as_Local() &&
1623       receiver->as_Local()->java_index() == 0) {
1624     ciInstanceKlass* ik = compilation()->method()->holder();
1625     if (ik->is_final()) {
1626       exact_type = ik;
1627     } else if (UseCHA && !(ik->has_subklass() || ik->is_interface())) {
1628       // test class is leaf class
1629       compilation()->dependency_recorder()->assert_leaf_type(ik);
1630       exact_type = ik;
1631     } else {
1632       declared_type = ik;
1633     }
1634   }
1635 
1636   // see if we know statically that registration isn't required
1637   bool needs_check = true;
1638   if (exact_type != nullptr) {
1639     needs_check = exact_type->as_instance_klass()->has_finalizer();
1640   } else if (declared_type != nullptr) {
1641     ciInstanceKlass* ik = declared_type->as_instance_klass();
1642     if (!Dependencies::has_finalizable_subclass(ik)) {
1643       compilation()->dependency_recorder()->assert_has_no_finalizable_subclasses(ik);
1644       needs_check = false;
1645     }
1646   }
1647 
1648   if (needs_check) {
1649     // Perform the registration of finalizable objects.
1650     ValueStack* state_before = copy_state_for_exception();
1651     load_local(objectType, 0);
1652     append_split(new Intrinsic(voidType, vmIntrinsics::_Object_init,
1653                                state()->pop_arguments(1),
1654                                true, state_before, true));
1655   }
1656 }
1657 
1658 
1659 void GraphBuilder::method_return(Value x, bool ignore_return) {
1660   if (RegisterFinalizersAtInit &&
1661       method()->intrinsic_id() == vmIntrinsics::_Object_init) {
1662     call_register_finalizer();
1663   }
1664 
1665   // The conditions for a memory barrier are described in Parse::do_exits().
1666   bool need_mem_bar = false;
1667   if (method()->is_object_constructor() &&
1668        (scope()->wrote_final() ||
1669          (AlwaysSafeConstructors && scope()->wrote_fields()) ||
1670          (support_IRIW_for_not_multiple_copy_atomic_cpu && scope()->wrote_volatile()))) {
1671     need_mem_bar = true;
1672   }
1673 
1674   BasicType bt = method()->return_type()->basic_type();
1675   switch (bt) {
1676     case T_BYTE:
1677     {
1678       Value shift = append(new Constant(new IntConstant(24)));
1679       x = append(new ShiftOp(Bytecodes::_ishl, x, shift));
1680       x = append(new ShiftOp(Bytecodes::_ishr, x, shift));
1681       break;
1682     }
1683     case T_SHORT:
1684     {
1685       Value shift = append(new Constant(new IntConstant(16)));
1686       x = append(new ShiftOp(Bytecodes::_ishl, x, shift));
1687       x = append(new ShiftOp(Bytecodes::_ishr, x, shift));
1688       break;
1689     }
1690     case T_CHAR:
1691     {
1692       Value mask = append(new Constant(new IntConstant(0xFFFF)));
1693       x = append(new LogicOp(Bytecodes::_iand, x, mask));
1694       break;
1695     }
1696     case T_BOOLEAN:
1697     {
1698       Value mask = append(new Constant(new IntConstant(1)));
1699       x = append(new LogicOp(Bytecodes::_iand, x, mask));
1700       break;
1701     }
1702     default:
1703       break;
1704   }
1705 
1706   // Check to see whether we are inlining. If so, Return
1707   // instructions become Gotos to the continuation point.
1708   if (continuation() != nullptr) {
1709 
1710     int invoke_bci = state()->caller_state()->bci();
1711 
1712     if (x != nullptr  && !ignore_return) {
1713       ciMethod* caller = state()->scope()->caller()->method();
1714       Bytecodes::Code invoke_raw_bc = caller->raw_code_at_bci(invoke_bci);
1715       if (invoke_raw_bc == Bytecodes::_invokehandle || invoke_raw_bc == Bytecodes::_invokedynamic) {
1716         ciType* declared_ret_type = caller->get_declared_signature_at_bci(invoke_bci)->return_type();
1717         if (declared_ret_type->is_klass() && x->exact_type() == nullptr &&
1718             x->declared_type() != declared_ret_type && declared_ret_type != compilation()->env()->Object_klass()) {
1719           x = append(new TypeCast(declared_ret_type->as_klass(), x, copy_state_before()));
1720         }
1721       }
1722     }
1723 
1724     assert(!method()->is_synchronized() || InlineSynchronizedMethods, "can not inline synchronized methods yet");
1725 
1726     if (compilation()->env()->dtrace_method_probes()) {
1727       // Report exit from inline methods
1728       Values* args = new Values(1);
1729       args->push(append(new Constant(new MethodConstant(method()))));
1730       append(new RuntimeCall(voidType, "dtrace_method_exit", CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit), args));
1731     }
1732 
1733     // If the inlined method is synchronized, the monitor must be
1734     // released before we jump to the continuation block.
1735     if (method()->is_synchronized()) {
1736       assert(state()->locks_size() == 1, "receiver must be locked here");
1737       monitorexit(state()->lock_at(0), SynchronizationEntryBCI);
1738     }
1739 
1740     if (need_mem_bar) {
1741       append(new MemBar(lir_membar_storestore));
1742     }
1743 
1744     // State at end of inlined method is the state of the caller
1745     // without the method parameters on stack, including the
1746     // return value, if any, of the inlined method on operand stack.
1747     set_state(state()->caller_state()->copy_for_parsing());
1748     if (x != nullptr) {
1749       if (!ignore_return) {
1750         state()->push(x->type(), x);
1751       }
1752       if (profile_return() && x->type()->is_object_kind()) {
1753         ciMethod* caller = state()->scope()->method();
1754         profile_return_type(x, method(), caller, invoke_bci);
1755       }
1756     }
1757     Goto* goto_callee = new Goto(continuation(), false);
1758 
1759     // See whether this is the first return; if so, store off some
1760     // of the state for later examination
1761     if (num_returns() == 0) {
1762       set_inline_cleanup_info();
1763     }
1764 
1765     // The current bci() is in the wrong scope, so use the bci() of
1766     // the continuation point.
1767     append_with_bci(goto_callee, scope_data()->continuation()->bci());
1768     incr_num_returns();
1769     return;
1770   }
1771 
1772   state()->truncate_stack(0);
1773   if (method()->is_synchronized()) {
1774     // perform the unlocking before exiting the method
1775     Value receiver;
1776     if (!method()->is_static()) {
1777       receiver = _initial_state->local_at(0);
1778     } else {
1779       receiver = append(new Constant(new ClassConstant(method()->holder())));
1780     }
1781     append_split(new MonitorExit(receiver, state()->unlock()));
1782   }
1783 
1784   if (need_mem_bar) {
1785       append(new MemBar(lir_membar_storestore));
1786   }
1787 
1788   assert(!ignore_return, "Ignoring return value works only for inlining");
1789   append(new Return(x));
1790 }
1791 
1792 Value GraphBuilder::make_constant(ciConstant field_value, ciField* field) {
1793   if (!field_value.is_valid())  return nullptr;
1794 
1795   BasicType field_type = field_value.basic_type();
1796   ValueType* value = as_ValueType(field_value);
1797 
1798   // Attach dimension info to stable arrays.
1799   if (FoldStableValues &&
1800       field->is_stable() && field_type == T_ARRAY && !field_value.is_null_or_zero()) {
1801     ciArray* array = field_value.as_object()->as_array();
1802     jint dimension = field->type()->as_array_klass()->dimension();
1803     value = new StableArrayConstant(array, dimension);
1804   }
1805 
1806   switch (field_type) {
1807     case T_ARRAY:
1808     case T_OBJECT:
1809       if (field_value.as_object()->should_be_constant()) {
1810         return new Constant(value);
1811       }
1812       return nullptr; // Not a constant.
1813     default:
1814       return new Constant(value);
1815   }
1816 }
1817 
1818 void GraphBuilder::copy_inline_content(ciInlineKlass* vk, Value src, int src_off, Value dest, int dest_off, ValueStack* state_before, ciField* enclosing_field) {
1819   for (int i = 0; i < vk->nof_nonstatic_fields(); i++) {
1820     ciField* inner_field = vk->nonstatic_field_at(i);
1821     assert(!inner_field->is_flat(), "the iteration over nested fields is handled by the loop itself");
1822     int off = inner_field->offset_in_bytes() - vk->first_field_offset();
1823     LoadField* load = new LoadField(src, src_off + off, inner_field, false, state_before, false);
1824     Value replacement = append(load);
1825     StoreField* store = new StoreField(dest, dest_off + off, inner_field, replacement, false, state_before, false);
1826     store->set_enclosing_field(enclosing_field);
1827     append(store);
1828   }
1829 }
1830 
1831 void GraphBuilder::access_field(Bytecodes::Code code) {
1832   bool will_link;
1833   ciField* field = stream()->get_field(will_link);
1834   ciInstanceKlass* holder = field->holder();
1835   BasicType field_type = field->type()->basic_type();
1836   ValueType* type = as_ValueType(field_type);
1837 
1838   // call will_link again to determine if the field is valid.
1839   const bool needs_patching = !holder->is_loaded() ||
1840                               !field->will_link(method(), code) ||
1841                               (!field->is_flat() && PatchALot);
1842 
1843   ValueStack* state_before = nullptr;
1844   if (!holder->is_initialized() || needs_patching) {
1845     // save state before instruction for debug info when
1846     // deoptimization happens during patching
1847     state_before = copy_state_before();
1848   }
1849 
1850   Value obj = nullptr;
1851   if (code == Bytecodes::_getstatic || code == Bytecodes::_putstatic) {
1852     if (state_before != nullptr) {
1853       // build a patching constant
1854       obj = new Constant(new InstanceConstant(holder->java_mirror()), state_before);
1855     } else {
1856       obj = new Constant(new InstanceConstant(holder->java_mirror()));
1857     }
1858   }
1859 
1860   if (field->is_final() && code == Bytecodes::_putfield) {
1861     scope()->set_wrote_final();
1862   }
1863 
1864   if (code == Bytecodes::_putfield) {
1865     scope()->set_wrote_fields();
1866     if (field->is_volatile()) {
1867       scope()->set_wrote_volatile();
1868     }
1869   }
1870 
1871   int offset = !needs_patching ? field->offset_in_bytes() : -1;
1872   switch (code) {
1873     case Bytecodes::_getstatic: {
1874       // check for compile-time constants, i.e., initialized static final fields
1875       Value constant = nullptr;
1876       if (field->is_static_constant() && !PatchALot) {
1877         ciConstant field_value = field->constant_value();
1878         assert(!field->is_stable() || !field_value.is_null_or_zero(),
1879                "stable static w/ default value shouldn't be a constant");
1880         constant = make_constant(field_value, field);
1881       } else if (field->is_null_free() && field->type()->as_instance_klass()->is_initialized() &&
1882                  field->type()->as_inline_klass()->is_empty()) {
1883         // Loading from a field of an empty inline type. Just return the default instance.
1884         constant = new Constant(new InstanceConstant(field->type()->as_inline_klass()->default_instance()));
1885       }
1886       if (constant != nullptr) {
1887         push(type, append(constant));
1888       } else {
1889         if (state_before == nullptr) {
1890           state_before = copy_state_for_exception();
1891         }
1892         LoadField* load_field = new LoadField(append(obj), offset, field, true,
1893                                         state_before, needs_patching);
1894         push(type, append(load_field));
1895       }
1896       break;
1897     }
1898     case Bytecodes::_putstatic: {
1899       Value val = pop(type);
1900       if (state_before == nullptr) {
1901         state_before = copy_state_for_exception();
1902       }
1903       if (field_type == T_BOOLEAN) {
1904         Value mask = append(new Constant(new IntConstant(1)));
1905         val = append(new LogicOp(Bytecodes::_iand, val, mask));
1906       }
1907       if (field->is_null_free()) {
1908         null_check(val);
1909       }
1910       if (field->is_null_free() && field->type()->is_loaded() && field->type()->as_inline_klass()->is_empty()) {
1911         // Storing to a field of an empty inline type. Ignore.
1912         break;
1913       }
1914       append(new StoreField(append(obj), offset, field, val, true, state_before, needs_patching));
1915       break;
1916     }
1917     case Bytecodes::_getfield: {
1918       // Check for compile-time constants, i.e., trusted final non-static fields.
1919       Value constant = nullptr;
1920       if (state_before == nullptr && field->is_flat()) {
1921         // Save the entire state and re-execute on deopt when accessing flat fields
1922         assert(Interpreter::bytecode_should_reexecute(code), "should reexecute");
1923         state_before = copy_state_before();
1924       }
1925       if (!has_pending_field_access() && !has_pending_load_indexed()) {
1926         obj = apop();
1927         ObjectType* obj_type = obj->type()->as_ObjectType();
1928         if (field->is_null_free() && field->type()->as_instance_klass()->is_initialized()
1929             && field->type()->as_inline_klass()->is_empty()) {
1930           // Loading from a field of an empty inline type. Just return the default instance.
1931           null_check(obj);
1932           constant = new Constant(new InstanceConstant(field->type()->as_inline_klass()->default_instance()));
1933         } else if (field->is_constant() && !field->is_flat() && obj_type->is_constant() && !PatchALot) {
1934           ciObject* const_oop = obj_type->constant_value();
1935           if (!const_oop->is_null_object() && const_oop->is_loaded()) {
1936             ciConstant field_value = field->constant_value_of(const_oop);
1937             if (field_value.is_valid()) {
1938               if (field->is_null_free() && field_value.is_null_or_zero()) {
1939                 // Non-flat inline type field. Replace null by the default value.
1940                 constant = new Constant(new InstanceConstant(field->type()->as_inline_klass()->default_instance()));
1941               } else {
1942                 constant = make_constant(field_value, field);
1943               }
1944               // For CallSite objects add a dependency for invalidation of the optimization.
1945               if (field->is_call_site_target()) {
1946                 ciCallSite* call_site = const_oop->as_call_site();
1947                 if (!call_site->is_fully_initialized_constant_call_site()) {
1948                   ciMethodHandle* target = field_value.as_object()->as_method_handle();
1949                   dependency_recorder()->assert_call_site_target_value(call_site, target);
1950                 }
1951               }
1952             }
1953           }
1954         }
1955       }
1956       if (constant != nullptr) {
1957         push(type, append(constant));
1958       } else {
1959         if (state_before == nullptr) {
1960           state_before = copy_state_for_exception();
1961         }
1962         if (!field->is_flat()) {
1963           if (has_pending_field_access()) {
1964             assert(!needs_patching, "Can't patch delayed field access");
1965             obj = pending_field_access()->obj();
1966             offset += pending_field_access()->offset() - field->holder()->as_inline_klass()->first_field_offset();
1967             field = pending_field_access()->holder()->get_field_by_offset(offset, false);
1968             assert(field != nullptr, "field not found");
1969             set_pending_field_access(nullptr);
1970           } else if (has_pending_load_indexed()) {
1971             assert(!needs_patching, "Can't patch delayed field access");
1972             pending_load_indexed()->update(field, offset - field->holder()->as_inline_klass()->first_field_offset());
1973             LoadIndexed* li = pending_load_indexed()->load_instr();
1974             li->set_type(type);
1975             push(type, append(li));
1976             set_pending_load_indexed(nullptr);
1977             break;
1978           }
1979           LoadField* load = new LoadField(obj, offset, field, false, state_before, needs_patching);
1980           Value replacement = !needs_patching ? _memory->load(load) : load;
1981           if (replacement != load) {
1982             assert(replacement->is_linked() || !replacement->can_be_linked(), "should already by linked");
1983             // Writing an (integer) value to a boolean, byte, char or short field includes an implicit narrowing
1984             // conversion. Emit an explicit conversion here to get the correct field value after the write.
1985             switch (field_type) {
1986             case T_BOOLEAN:
1987             case T_BYTE:
1988               replacement = append(new Convert(Bytecodes::_i2b, replacement, type));
1989               break;
1990             case T_CHAR:
1991               replacement = append(new Convert(Bytecodes::_i2c, replacement, type));
1992               break;
1993             case T_SHORT:
1994               replacement = append(new Convert(Bytecodes::_i2s, replacement, type));
1995               break;
1996             default:
1997               break;
1998             }
1999             push(type, replacement);
2000           } else {
2001             push(type, append(load));
2002           }
2003         } else {  // field is flat
2004           // Look at the next bytecode to check if we can delay the field access
2005           bool can_delay_access = false;
2006           ciBytecodeStream s(method());
2007           s.force_bci(bci());
2008           s.next();
2009           if (s.cur_bc() == Bytecodes::_getfield && !needs_patching) {
2010             ciField* next_field = s.get_field(will_link);
2011             bool next_needs_patching = !next_field->holder()->is_loaded() ||
2012                                        !next_field->will_link(method(), Bytecodes::_getfield) ||
2013                                        PatchALot;
2014             can_delay_access = C1UseDelayedFlattenedFieldReads && !next_needs_patching;
2015           }
2016           if (can_delay_access) {
2017             if (has_pending_load_indexed()) {
2018               pending_load_indexed()->update(field, offset - field->holder()->as_inline_klass()->first_field_offset());
2019             } else if (has_pending_field_access()) {
2020               pending_field_access()->inc_offset(offset - field->holder()->as_inline_klass()->first_field_offset());
2021             } else {
2022               null_check(obj);
2023               DelayedFieldAccess* dfa = new DelayedFieldAccess(obj, field->holder(), field->offset_in_bytes(), state_before);
2024               set_pending_field_access(dfa);
2025             }
2026           } else {
2027             ciInlineKlass* inline_klass = field->type()->as_inline_klass();
2028             scope()->set_wrote_final();
2029             scope()->set_wrote_fields();
2030             bool need_membar = false;
2031             if (inline_klass->is_initialized() && inline_klass->is_empty()) {
2032               apush(append(new Constant(new InstanceConstant(inline_klass->default_instance()))));
2033               if (has_pending_field_access()) {
2034                 set_pending_field_access(nullptr);
2035               } else if (has_pending_load_indexed()) {
2036                 set_pending_load_indexed(nullptr);
2037               }
2038             } else if (has_pending_load_indexed()) {
2039               assert(!needs_patching, "Can't patch delayed field access");
2040               pending_load_indexed()->update(field, offset - field->holder()->as_inline_klass()->first_field_offset());
2041               NewInstance* vt = new NewInstance(inline_klass, pending_load_indexed()->state_before(), false, true);
2042               _memory->new_instance(vt);
2043               pending_load_indexed()->load_instr()->set_vt(vt);
2044               apush(append_split(vt));
2045               append(pending_load_indexed()->load_instr());
2046               set_pending_load_indexed(nullptr);
2047               need_membar = true;
2048             } else {
2049               if (has_pending_field_access()) {
2050                 state_before = pending_field_access()->state_before();
2051               }
2052               NewInstance* new_instance = new NewInstance(inline_klass, state_before, false, true);
2053               _memory->new_instance(new_instance);
2054               apush(append_split(new_instance));
2055               assert(!needs_patching, "Can't patch flat inline type field access");
2056               if (has_pending_field_access()) {
2057                 copy_inline_content(inline_klass, pending_field_access()->obj(),
2058                                     pending_field_access()->offset() + field->offset_in_bytes() - field->holder()->as_inline_klass()->first_field_offset(),
2059                                     new_instance, inline_klass->first_field_offset(), state_before);
2060                 set_pending_field_access(nullptr);
2061               } else {
2062                 copy_inline_content(inline_klass, obj, field->offset_in_bytes(), new_instance, inline_klass->first_field_offset(), state_before);
2063               }
2064               need_membar = true;
2065             }
2066             if (need_membar) {
2067               // If we allocated a new instance ensure the stores to copy the
2068               // field contents are visible before any subsequent store that
2069               // publishes this reference.
2070               append(new MemBar(lir_membar_storestore));
2071             }
2072           }
2073         }
2074       }
2075       break;
2076     }
2077     case Bytecodes::_putfield: {
2078       Value val = pop(type);
2079       obj = apop();
2080       if (state_before == nullptr) {
2081         state_before = copy_state_for_exception();
2082       }
2083       if (field_type == T_BOOLEAN) {
2084         Value mask = append(new Constant(new IntConstant(1)));
2085         val = append(new LogicOp(Bytecodes::_iand, val, mask));
2086       }
2087       if (field->is_null_free() && field->type()->is_loaded() && field->type()->as_inline_klass()->is_empty()) {
2088         // Storing to a field of an empty inline type. Ignore.
2089         null_check(obj);
2090         null_check(val);
2091       } else if (!field->is_flat()) {
2092         if (field->is_null_free()) {
2093           null_check(val);
2094         }
2095         StoreField* store = new StoreField(obj, offset, field, val, false, state_before, needs_patching);
2096         if (!needs_patching) store = _memory->store(store);
2097         if (store != nullptr) {
2098           append(store);
2099         }
2100       } else {
2101         assert(!needs_patching, "Can't patch flat inline type field access");
2102         ciInlineKlass* inline_klass = field->type()->as_inline_klass();
2103         copy_inline_content(inline_klass, val, inline_klass->first_field_offset(), obj, offset, state_before, field);
2104       }
2105       break;
2106     }
2107     default:
2108       ShouldNotReachHere();
2109       break;
2110   }
2111 }
2112 
2113 Dependencies* GraphBuilder::dependency_recorder() const {
2114   assert(DeoptC1, "need debug information");
2115   return compilation()->dependency_recorder();
2116 }
2117 
2118 // How many arguments do we want to profile?
2119 Values* GraphBuilder::args_list_for_profiling(ciMethod* target, int& start, bool may_have_receiver) {
2120   int n = 0;
2121   bool has_receiver = may_have_receiver && Bytecodes::has_receiver(method()->java_code_at_bci(bci()));
2122   start = has_receiver ? 1 : 0;
2123   if (profile_arguments()) {
2124     ciProfileData* data = method()->method_data()->bci_to_data(bci());
2125     if (data != nullptr && (data->is_CallTypeData() || data->is_VirtualCallTypeData())) {
2126       n = data->is_CallTypeData() ? data->as_CallTypeData()->number_of_arguments() : data->as_VirtualCallTypeData()->number_of_arguments();
2127     }
2128   }
2129   // If we are inlining then we need to collect arguments to profile parameters for the target
2130   if (profile_parameters() && target != nullptr) {
2131     if (target->method_data() != nullptr && target->method_data()->parameters_type_data() != nullptr) {
2132       // The receiver is profiled on method entry so it's included in
2133       // the number of parameters but here we're only interested in
2134       // actual arguments.
2135       n = MAX2(n, target->method_data()->parameters_type_data()->number_of_parameters() - start);
2136     }
2137   }
2138   if (n > 0) {
2139     return new Values(n);
2140   }
2141   return nullptr;
2142 }
2143 
2144 void GraphBuilder::check_args_for_profiling(Values* obj_args, int expected) {
2145 #ifdef ASSERT
2146   bool ignored_will_link;
2147   ciSignature* declared_signature = nullptr;
2148   ciMethod* real_target = method()->get_method_at_bci(bci(), ignored_will_link, &declared_signature);
2149   assert(expected == obj_args->capacity() || real_target->is_method_handle_intrinsic(), "missed on arg?");
2150 #endif
2151 }
2152 
2153 // Collect arguments that we want to profile in a list
2154 Values* GraphBuilder::collect_args_for_profiling(Values* args, ciMethod* target, bool may_have_receiver) {
2155   int start = 0;
2156   Values* obj_args = args_list_for_profiling(target, start, may_have_receiver);
2157   if (obj_args == nullptr) {
2158     return nullptr;
2159   }
2160   int s = obj_args->capacity();
2161   // if called through method handle invoke, some arguments may have been popped
2162   for (int i = start, j = 0; j < s && i < args->length(); i++) {
2163     if (args->at(i)->type()->is_object_kind()) {
2164       obj_args->push(args->at(i));
2165       j++;
2166     }
2167   }
2168   check_args_for_profiling(obj_args, s);
2169   return obj_args;
2170 }
2171 
2172 void GraphBuilder::invoke(Bytecodes::Code code) {
2173   bool will_link;
2174   ciSignature* declared_signature = nullptr;
2175   ciMethod*             target = stream()->get_method(will_link, &declared_signature);
2176   ciKlass*              holder = stream()->get_declared_method_holder();
2177   const Bytecodes::Code bc_raw = stream()->cur_bc_raw();
2178   assert(declared_signature != nullptr, "cannot be null");
2179   assert(will_link == target->is_loaded(), "");
2180   JFR_ONLY(Jfr::on_resolution(this, holder, target); CHECK_BAILOUT();)
2181 
2182   ciInstanceKlass* klass = target->holder();
2183   assert(!target->is_loaded() || klass->is_loaded(), "loaded target must imply loaded klass");
2184 
2185   // check if CHA possible: if so, change the code to invoke_special
2186   ciInstanceKlass* calling_klass = method()->holder();
2187   ciInstanceKlass* callee_holder = ciEnv::get_instance_klass_for_declared_method_holder(holder);
2188   ciInstanceKlass* actual_recv = callee_holder;
2189 
2190   CompileLog* log = compilation()->log();
2191   if (log != nullptr)
2192       log->elem("call method='%d' instr='%s'",
2193                 log->identify(target),
2194                 Bytecodes::name(code));
2195 
2196   // Some methods are obviously bindable without any type checks so
2197   // convert them directly to an invokespecial or invokestatic.
2198   if (target->is_loaded() && !target->is_abstract() && target->can_be_statically_bound()) {
2199     switch (bc_raw) {
2200     case Bytecodes::_invokeinterface:
2201       // convert to invokespecial if the target is the private interface method.
2202       if (target->is_private()) {
2203         assert(holder->is_interface(), "How did we get a non-interface method here!");
2204         code = Bytecodes::_invokespecial;
2205       }
2206       break;
2207     case Bytecodes::_invokevirtual:
2208       code = Bytecodes::_invokespecial;
2209       break;
2210     case Bytecodes::_invokehandle:
2211       code = target->is_static() ? Bytecodes::_invokestatic : Bytecodes::_invokespecial;
2212       break;
2213     default:
2214       break;
2215     }
2216   } else {
2217     if (bc_raw == Bytecodes::_invokehandle) {
2218       assert(!will_link, "should come here only for unlinked call");
2219       code = Bytecodes::_invokespecial;
2220     }
2221   }
2222 
2223   if (code == Bytecodes::_invokespecial) {
2224     // Additional receiver subtype checks for interface calls via invokespecial or invokeinterface.
2225     ciKlass* receiver_constraint = nullptr;
2226 
2227     if (bc_raw == Bytecodes::_invokeinterface) {
2228       receiver_constraint = holder;
2229     } else if (bc_raw == Bytecodes::_invokespecial && !target->is_object_constructor() && calling_klass->is_interface()) {
2230       receiver_constraint = calling_klass;
2231     }
2232 
2233     if (receiver_constraint != nullptr) {
2234       int index = state()->stack_size() - (target->arg_size_no_receiver() + 1);
2235       Value receiver = state()->stack_at(index);
2236       CheckCast* c = new CheckCast(receiver_constraint, receiver, copy_state_before());
2237       // go to uncommon_trap when checkcast fails
2238       c->set_invokespecial_receiver_check();
2239       state()->stack_at_put(index, append_split(c));
2240     }
2241   }
2242 
2243   // Push appendix argument (MethodType, CallSite, etc.), if one.
2244   bool patch_for_appendix = false;
2245   int patching_appendix_arg = 0;
2246   if (Bytecodes::has_optional_appendix(bc_raw) && (!will_link || PatchALot)) {
2247     Value arg = append(new Constant(new ObjectConstant(compilation()->env()->unloaded_ciinstance()), copy_state_before()));
2248     apush(arg);
2249     patch_for_appendix = true;
2250     patching_appendix_arg = (will_link && stream()->has_appendix()) ? 0 : 1;
2251   } else if (stream()->has_appendix()) {
2252     ciObject* appendix = stream()->get_appendix();
2253     Value arg = append(new Constant(new ObjectConstant(appendix)));
2254     apush(arg);
2255   }
2256 
2257   ciMethod* cha_monomorphic_target = nullptr;
2258   ciMethod* exact_target = nullptr;
2259   Value better_receiver = nullptr;
2260   if (UseCHA && DeoptC1 && target->is_loaded() &&
2261       !(// %%% FIXME: Are both of these relevant?
2262         target->is_method_handle_intrinsic() ||
2263         target->is_compiled_lambda_form()) &&
2264       !patch_for_appendix) {
2265     Value receiver = nullptr;
2266     ciInstanceKlass* receiver_klass = nullptr;
2267     bool type_is_exact = false;
2268     // try to find a precise receiver type
2269     if (will_link && !target->is_static()) {
2270       int index = state()->stack_size() - (target->arg_size_no_receiver() + 1);
2271       receiver = state()->stack_at(index);
2272       ciType* type = receiver->exact_type();
2273       if (type != nullptr && type->is_loaded() &&
2274           type->is_instance_klass() && !type->as_instance_klass()->is_interface()) {
2275         receiver_klass = (ciInstanceKlass*) type;
2276         type_is_exact = true;
2277       }
2278       if (type == nullptr) {
2279         type = receiver->declared_type();
2280         if (type != nullptr && type->is_loaded() &&
2281             type->is_instance_klass() && !type->as_instance_klass()->is_interface()) {
2282           receiver_klass = (ciInstanceKlass*) type;
2283           if (receiver_klass->is_leaf_type() && !receiver_klass->is_final()) {
2284             // Insert a dependency on this type since
2285             // find_monomorphic_target may assume it's already done.
2286             dependency_recorder()->assert_leaf_type(receiver_klass);
2287             type_is_exact = true;
2288           }
2289         }
2290       }
2291     }
2292     if (receiver_klass != nullptr && type_is_exact &&
2293         receiver_klass->is_loaded() && code != Bytecodes::_invokespecial) {
2294       // If we have the exact receiver type we can bind directly to
2295       // the method to call.
2296       exact_target = target->resolve_invoke(calling_klass, receiver_klass);
2297       if (exact_target != nullptr) {
2298         target = exact_target;
2299         code = Bytecodes::_invokespecial;
2300       }
2301     }
2302     if (receiver_klass != nullptr &&
2303         receiver_klass->is_subtype_of(actual_recv) &&
2304         actual_recv->is_initialized()) {
2305       actual_recv = receiver_klass;
2306     }
2307 
2308     if ((code == Bytecodes::_invokevirtual && callee_holder->is_initialized()) ||
2309         (code == Bytecodes::_invokeinterface && callee_holder->is_initialized() && !actual_recv->is_interface())) {
2310       // Use CHA on the receiver to select a more precise method.
2311       cha_monomorphic_target = target->find_monomorphic_target(calling_klass, callee_holder, actual_recv);
2312     } else if (code == Bytecodes::_invokeinterface && callee_holder->is_loaded() && receiver != nullptr) {
2313       assert(callee_holder->is_interface(), "invokeinterface to non interface?");
2314       // If there is only one implementor of this interface then we
2315       // may be able bind this invoke directly to the implementing
2316       // klass but we need both a dependence on the single interface
2317       // and on the method we bind to.  Additionally since all we know
2318       // about the receiver type is the it's supposed to implement the
2319       // interface we have to insert a check that it's the class we
2320       // expect.  Interface types are not checked by the verifier so
2321       // they are roughly equivalent to Object.
2322       // The number of implementors for declared_interface is less or
2323       // equal to the number of implementors for target->holder() so
2324       // if number of implementors of target->holder() == 1 then
2325       // number of implementors for decl_interface is 0 or 1. If
2326       // it's 0 then no class implements decl_interface and there's
2327       // no point in inlining.
2328       ciInstanceKlass* declared_interface = callee_holder;
2329       ciInstanceKlass* singleton = declared_interface->unique_implementor();
2330       if (singleton != nullptr) {
2331         assert(singleton != declared_interface, "not a unique implementor");
2332         cha_monomorphic_target = target->find_monomorphic_target(calling_klass, declared_interface, singleton);
2333         if (cha_monomorphic_target != nullptr) {
2334           ciInstanceKlass* holder = cha_monomorphic_target->holder();
2335           ciInstanceKlass* constraint = (holder->is_subtype_of(singleton) ? holder : singleton); // avoid upcasts
2336           if (holder != compilation()->env()->Object_klass() &&
2337               (!type_is_exact || receiver_klass->is_subtype_of(constraint))) {
2338             actual_recv = declared_interface;
2339 
2340             // insert a check it's really the expected class.
2341             CheckCast* c = new CheckCast(constraint, receiver, copy_state_for_exception());
2342             c->set_incompatible_class_change_check();
2343             c->set_direct_compare(constraint->is_final());
2344             // pass the result of the checkcast so that the compiler has
2345             // more accurate type info in the inlinee
2346             better_receiver = append_split(c);
2347 
2348             dependency_recorder()->assert_unique_implementor(declared_interface, singleton);
2349           } else {
2350             cha_monomorphic_target = nullptr;
2351           }
2352         }
2353       }
2354     }
2355   }
2356 
2357   if (cha_monomorphic_target != nullptr) {
2358     assert(!target->can_be_statically_bound() || target == cha_monomorphic_target, "");
2359     assert(!cha_monomorphic_target->is_abstract(), "");
2360     if (!cha_monomorphic_target->can_be_statically_bound(actual_recv)) {
2361       // If we inlined because CHA revealed only a single target method,
2362       // then we are dependent on that target method not getting overridden
2363       // by dynamic class loading.  Be sure to test the "static" receiver
2364       // dest_method here, as opposed to the actual receiver, which may
2365       // falsely lead us to believe that the receiver is final or private.
2366       dependency_recorder()->assert_unique_concrete_method(actual_recv, cha_monomorphic_target, callee_holder, target);
2367     }
2368     code = Bytecodes::_invokespecial;
2369   }
2370 
2371   // check if we could do inlining
2372   if (!PatchALot && Inline && target->is_loaded() && !patch_for_appendix &&
2373       callee_holder->is_loaded()) { // the effect of symbolic reference resolution
2374 
2375     // callee is known => check if we have static binding
2376     if ((code == Bytecodes::_invokestatic && klass->is_initialized()) || // invokestatic involves an initialization barrier on declaring class
2377         code == Bytecodes::_invokespecial ||
2378         (code == Bytecodes::_invokevirtual && target->is_final_method()) ||
2379         code == Bytecodes::_invokedynamic) {
2380       // static binding => check if callee is ok
2381       ciMethod* inline_target = (cha_monomorphic_target != nullptr) ? cha_monomorphic_target : target;
2382       bool holder_known = (cha_monomorphic_target != nullptr) || (exact_target != nullptr);
2383       bool success = try_inline(inline_target, holder_known, false /* ignore_return */, code, better_receiver);
2384 
2385       CHECK_BAILOUT();
2386       clear_inline_bailout();
2387 
2388       if (success) {
2389         // Register dependence if JVMTI has either breakpoint
2390         // setting or hotswapping of methods capabilities since they may
2391         // cause deoptimization.
2392         if (compilation()->env()->jvmti_can_hotswap_or_post_breakpoint()) {
2393           dependency_recorder()->assert_evol_method(inline_target);
2394         }
2395         return;
2396       }
2397     } else {
2398       print_inlining(target, "no static binding", /*success*/ false);
2399     }
2400   } else {
2401     print_inlining(target, "not inlineable", /*success*/ false);
2402   }
2403 
2404   // If we attempted an inline which did not succeed because of a
2405   // bailout during construction of the callee graph, the entire
2406   // compilation has to be aborted. This is fairly rare and currently
2407   // seems to only occur for jasm-generated classes which contain
2408   // jsr/ret pairs which are not associated with finally clauses and
2409   // do not have exception handlers in the containing method, and are
2410   // therefore not caught early enough to abort the inlining without
2411   // corrupting the graph. (We currently bail out with a non-empty
2412   // stack at a ret in these situations.)
2413   CHECK_BAILOUT();
2414 
2415   // inlining not successful => standard invoke
2416   ValueType* result_type = as_ValueType(declared_signature->return_type());
2417   ValueStack* state_before = copy_state_exhandling();
2418 
2419   // The bytecode (code) might change in this method so we are checking this very late.
2420   const bool has_receiver =
2421     code == Bytecodes::_invokespecial   ||
2422     code == Bytecodes::_invokevirtual   ||
2423     code == Bytecodes::_invokeinterface;
2424   Values* args = state()->pop_arguments(target->arg_size_no_receiver() + patching_appendix_arg);
2425   Value recv = has_receiver ? apop() : nullptr;
2426 
2427   // A null check is required here (when there is a receiver) for any of the following cases
2428   // - invokespecial, always need a null check.
2429   // - invokevirtual, when the target is final and loaded. Calls to final targets will become optimized
2430   //   and require null checking. If the target is loaded a null check is emitted here.
2431   //   If the target isn't loaded the null check must happen after the call resolution. We achieve that
2432   //   by using the target methods unverified entry point (see CompiledIC::compute_monomorphic_entry).
2433   //   (The JVM specification requires that LinkageError must be thrown before a NPE. An unloaded target may
2434   //   potentially fail, and can't have the null check before the resolution.)
2435   // - A call that will be profiled. (But we can't add a null check when the target is unloaded, by the same
2436   //   reason as above, so calls with a receiver to unloaded targets can't be profiled.)
2437   //
2438   // Normal invokevirtual will perform the null check during lookup
2439 
2440   bool need_null_check = (code == Bytecodes::_invokespecial) ||
2441       (target->is_loaded() && (target->is_final_method() || (is_profiling() && profile_calls())));
2442 
2443   if (need_null_check) {
2444     if (recv != nullptr) {
2445       null_check(recv);
2446     }
2447 
2448     if (is_profiling()) {
2449       // Note that we'd collect profile data in this method if we wanted it.
2450       compilation()->set_would_profile(true);
2451 
2452       if (profile_calls()) {
2453         assert(cha_monomorphic_target == nullptr || exact_target == nullptr, "both can not be set");
2454         ciKlass* target_klass = nullptr;
2455         if (cha_monomorphic_target != nullptr) {
2456           target_klass = cha_monomorphic_target->holder();
2457         } else if (exact_target != nullptr) {
2458           target_klass = exact_target->holder();
2459         }
2460         profile_call(target, recv, target_klass, collect_args_for_profiling(args, nullptr, false), false);
2461       }
2462     }
2463   }
2464 
2465   Invoke* result = new Invoke(code, result_type, recv, args, target, state_before);
2466   // push result
2467   append_split(result);
2468 
2469   if (result_type != voidType) {
2470     push(result_type, round_fp(result));
2471   }
2472   if (profile_return() && result_type->is_object_kind()) {
2473     profile_return_type(result, target);
2474   }
2475 }
2476 
2477 
2478 void GraphBuilder::new_instance(int klass_index) {
2479   ValueStack* state_before = copy_state_exhandling();
2480   ciKlass* klass = stream()->get_klass();
2481   assert(klass->is_instance_klass(), "must be an instance klass");
2482   if (!stream()->is_unresolved_klass() && klass->is_inlinetype() &&
2483       klass->as_inline_klass()->is_initialized() && klass->as_inline_klass()->is_empty()) {
2484     ciInlineKlass* vk = klass->as_inline_klass();
2485     apush(append(new Constant(new InstanceConstant(vk->default_instance()))));
2486   } else {
2487     NewInstance* new_instance = new NewInstance(klass->as_instance_klass(), state_before, stream()->is_unresolved_klass(), false);
2488     _memory->new_instance(new_instance);
2489     apush(append_split(new_instance));
2490   }
2491 }
2492 
2493 void GraphBuilder::new_type_array() {
2494   ValueStack* state_before = copy_state_exhandling();
2495   apush(append_split(new NewTypeArray(ipop(), (BasicType)stream()->get_index(), state_before)));
2496 }
2497 
2498 
2499 void GraphBuilder::new_object_array() {
2500   ciKlass* klass = stream()->get_klass();
2501   ValueStack* state_before = !klass->is_loaded() || PatchALot ? copy_state_before() : copy_state_exhandling();
2502   NewArray* n = new NewObjectArray(klass, ipop(), state_before);
2503   apush(append_split(n));
2504 }
2505 
2506 
2507 bool GraphBuilder::direct_compare(ciKlass* k) {
2508   if (k->is_loaded() && k->is_instance_klass() && !UseSlowPath) {
2509     ciInstanceKlass* ik = k->as_instance_klass();
2510     if (ik->is_final()) {
2511       return true;
2512     } else {
2513       if (DeoptC1 && UseCHA && !(ik->has_subklass() || ik->is_interface())) {
2514         // test class is leaf class
2515         dependency_recorder()->assert_leaf_type(ik);
2516         return true;
2517       }
2518     }
2519   }
2520   return false;
2521 }
2522 
2523 
2524 void GraphBuilder::check_cast(int klass_index) {
2525   ciKlass* klass = stream()->get_klass();
2526   ValueStack* state_before = !klass->is_loaded() || PatchALot ? copy_state_before() : copy_state_for_exception();
2527   CheckCast* c = new CheckCast(klass, apop(), state_before);
2528   apush(append_split(c));
2529   c->set_direct_compare(direct_compare(klass));
2530 
2531   if (is_profiling()) {
2532     // Note that we'd collect profile data in this method if we wanted it.
2533     compilation()->set_would_profile(true);
2534 
2535     if (profile_checkcasts()) {
2536       c->set_profiled_method(method());
2537       c->set_profiled_bci(bci());
2538       c->set_should_profile(true);
2539     }
2540   }
2541 }
2542 
2543 
2544 void GraphBuilder::instance_of(int klass_index) {
2545   ciKlass* klass = stream()->get_klass();
2546   ValueStack* state_before = !klass->is_loaded() || PatchALot ? copy_state_before() : copy_state_exhandling();
2547   InstanceOf* i = new InstanceOf(klass, apop(), state_before);
2548   ipush(append_split(i));
2549   i->set_direct_compare(direct_compare(klass));
2550 
2551   if (is_profiling()) {
2552     // Note that we'd collect profile data in this method if we wanted it.
2553     compilation()->set_would_profile(true);
2554 
2555     if (profile_checkcasts()) {
2556       i->set_profiled_method(method());
2557       i->set_profiled_bci(bci());
2558       i->set_should_profile(true);
2559     }
2560   }
2561 }
2562 
2563 
2564 void GraphBuilder::monitorenter(Value x, int bci) {
2565   bool maybe_inlinetype = false;
2566   if (bci == InvocationEntryBci) {
2567     // Called by GraphBuilder::inline_sync_entry.
2568 #ifdef ASSERT
2569     ciType* obj_type = x->declared_type();
2570     assert(obj_type == nullptr || !obj_type->is_inlinetype(), "inline types cannot have synchronized methods");
2571 #endif
2572   } else {
2573     // We are compiling a monitorenter bytecode
2574     if (EnableValhalla) {
2575       ciType* obj_type = x->declared_type();
2576       if (obj_type == nullptr || obj_type->as_klass()->can_be_inline_klass()) {
2577         // If we're (possibly) locking on an inline type, check for markWord::always_locked_pattern
2578         // and throw IMSE. (obj_type is null for Phi nodes, so let's just be conservative).
2579         maybe_inlinetype = true;
2580       }
2581     }
2582   }
2583 
2584   // save state before locking in case of deoptimization after a NullPointerException
2585   ValueStack* state_before = copy_state_for_exception_with_bci(bci);
2586   append_with_bci(new MonitorEnter(x, state()->lock(x), state_before, maybe_inlinetype), bci);
2587   kill_all();
2588 }
2589 
2590 
2591 void GraphBuilder::monitorexit(Value x, int bci) {
2592   append_with_bci(new MonitorExit(x, state()->unlock()), bci);
2593   kill_all();
2594 }
2595 
2596 
2597 void GraphBuilder::new_multi_array(int dimensions) {
2598   ciKlass* klass = stream()->get_klass();
2599   ValueStack* state_before = !klass->is_loaded() || PatchALot ? copy_state_before() : copy_state_exhandling();
2600 
2601   Values* dims = new Values(dimensions, dimensions, nullptr);
2602   // fill in all dimensions
2603   int i = dimensions;
2604   while (i-- > 0) dims->at_put(i, ipop());
2605   // create array
2606   NewArray* n = new NewMultiArray(klass, dims, state_before);
2607   apush(append_split(n));
2608 }
2609 
2610 
2611 void GraphBuilder::throw_op(int bci) {
2612   // We require that the debug info for a Throw be the "state before"
2613   // the Throw (i.e., exception oop is still on TOS)
2614   ValueStack* state_before = copy_state_before_with_bci(bci);
2615   Throw* t = new Throw(apop(), state_before);
2616   // operand stack not needed after a throw
2617   state()->truncate_stack(0);
2618   append_with_bci(t, bci);
2619 }
2620 
2621 
2622 Value GraphBuilder::round_fp(Value fp_value) {
2623   if (strict_fp_requires_explicit_rounding) {
2624 #ifdef IA32
2625     // no rounding needed if SSE2 is used
2626     if (UseSSE < 2) {
2627       // Must currently insert rounding node for doubleword values that
2628       // are results of expressions (i.e., not loads from memory or
2629       // constants)
2630       if (fp_value->type()->tag() == doubleTag &&
2631           fp_value->as_Constant() == nullptr &&
2632           fp_value->as_Local() == nullptr &&       // method parameters need no rounding
2633           fp_value->as_RoundFP() == nullptr) {
2634         return append(new RoundFP(fp_value));
2635       }
2636     }
2637 #else
2638     Unimplemented();
2639 #endif // IA32
2640   }
2641   return fp_value;
2642 }
2643 
2644 
2645 Instruction* GraphBuilder::append_with_bci(Instruction* instr, int bci) {
2646   Canonicalizer canon(compilation(), instr, bci);
2647   Instruction* i1 = canon.canonical();
2648   if (i1->is_linked() || !i1->can_be_linked()) {
2649     // Canonicalizer returned an instruction which was already
2650     // appended so simply return it.
2651     return i1;
2652   }
2653 
2654   if (UseLocalValueNumbering) {
2655     // Lookup the instruction in the ValueMap and add it to the map if
2656     // it's not found.
2657     Instruction* i2 = vmap()->find_insert(i1);
2658     if (i2 != i1) {
2659       // found an entry in the value map, so just return it.
2660       assert(i2->is_linked(), "should already be linked");
2661       return i2;
2662     }
2663     ValueNumberingEffects vne(vmap());
2664     i1->visit(&vne);
2665   }
2666 
2667   // i1 was not eliminated => append it
2668   assert(i1->next() == nullptr, "shouldn't already be linked");
2669   _last = _last->set_next(i1, canon.bci());
2670 
2671   if (++_instruction_count >= InstructionCountCutoff && !bailed_out()) {
2672     // set the bailout state but complete normal processing.  We
2673     // might do a little more work before noticing the bailout so we
2674     // want processing to continue normally until it's noticed.
2675     bailout("Method and/or inlining is too large");
2676   }
2677 
2678 #ifndef PRODUCT
2679   if (PrintIRDuringConstruction) {
2680     InstructionPrinter ip;
2681     ip.print_line(i1);
2682     if (Verbose) {
2683       state()->print();
2684     }
2685   }
2686 #endif
2687 
2688   // save state after modification of operand stack for StateSplit instructions
2689   StateSplit* s = i1->as_StateSplit();
2690   if (s != nullptr) {
2691     if (EliminateFieldAccess) {
2692       Intrinsic* intrinsic = s->as_Intrinsic();
2693       if (s->as_Invoke() != nullptr || (intrinsic && !intrinsic->preserves_state())) {
2694         _memory->kill();
2695       }
2696     }
2697     s->set_state(state()->copy(ValueStack::StateAfter, canon.bci()));
2698   }
2699 
2700   // set up exception handlers for this instruction if necessary
2701   if (i1->can_trap()) {
2702     i1->set_exception_handlers(handle_exception(i1));
2703     assert(i1->exception_state() != nullptr || !i1->needs_exception_state() || bailed_out(), "handle_exception must set exception state");
2704   }
2705   return i1;
2706 }
2707 
2708 
2709 Instruction* GraphBuilder::append(Instruction* instr) {
2710   assert(instr->as_StateSplit() == nullptr || instr->as_BlockEnd() != nullptr, "wrong append used");
2711   return append_with_bci(instr, bci());
2712 }
2713 
2714 
2715 Instruction* GraphBuilder::append_split(StateSplit* instr) {
2716   return append_with_bci(instr, bci());
2717 }
2718 
2719 
2720 void GraphBuilder::null_check(Value value) {
2721   if (value->as_NewArray() != nullptr || value->as_NewInstance() != nullptr) {
2722     return;
2723   } else {
2724     Constant* con = value->as_Constant();
2725     if (con) {
2726       ObjectType* c = con->type()->as_ObjectType();
2727       if (c && c->is_loaded()) {
2728         ObjectConstant* oc = c->as_ObjectConstant();
2729         if (!oc || !oc->value()->is_null_object()) {
2730           return;
2731         }
2732       }
2733     }
2734     if (value->is_null_free()) return;
2735   }
2736   append(new NullCheck(value, copy_state_for_exception()));
2737 }
2738 
2739 
2740 
2741 XHandlers* GraphBuilder::handle_exception(Instruction* instruction) {
2742   if (!has_handler() && (!instruction->needs_exception_state() || instruction->exception_state() != nullptr)) {
2743     assert(instruction->exception_state() == nullptr
2744            || instruction->exception_state()->kind() == ValueStack::EmptyExceptionState
2745            || (instruction->exception_state()->kind() == ValueStack::ExceptionState && _compilation->env()->should_retain_local_variables()),
2746            "exception_state should be of exception kind");
2747     return new XHandlers();
2748   }
2749 
2750   XHandlers*  exception_handlers = new XHandlers();
2751   ScopeData*  cur_scope_data = scope_data();
2752   ValueStack* cur_state = instruction->state_before();
2753   ValueStack* prev_state = nullptr;
2754   int scope_count = 0;
2755 
2756   assert(cur_state != nullptr, "state_before must be set");
2757   do {
2758     int cur_bci = cur_state->bci();
2759     assert(cur_scope_data->scope() == cur_state->scope(), "scopes do not match");
2760     assert(cur_bci == SynchronizationEntryBCI || cur_bci == cur_scope_data->stream()->cur_bci()
2761            || has_pending_field_access() || has_pending_load_indexed(), "invalid bci");
2762 
2763 
2764     // join with all potential exception handlers
2765     XHandlers* list = cur_scope_data->xhandlers();
2766     const int n = list->length();
2767     for (int i = 0; i < n; i++) {
2768       XHandler* h = list->handler_at(i);
2769       if (h->covers(cur_bci)) {
2770         // h is a potential exception handler => join it
2771         compilation()->set_has_exception_handlers(true);
2772 
2773         BlockBegin* entry = h->entry_block();
2774         if (entry == block()) {
2775           // It's acceptable for an exception handler to cover itself
2776           // but we don't handle that in the parser currently.  It's
2777           // very rare so we bailout instead of trying to handle it.
2778           BAILOUT_("exception handler covers itself", exception_handlers);
2779         }
2780         assert(entry->bci() == h->handler_bci(), "must match");
2781         assert(entry->bci() == -1 || entry == cur_scope_data->block_at(entry->bci()), "blocks must correspond");
2782 
2783         // previously this was a BAILOUT, but this is not necessary
2784         // now because asynchronous exceptions are not handled this way.
2785         assert(entry->state() == nullptr || cur_state->total_locks_size() == entry->state()->total_locks_size(), "locks do not match");
2786 
2787         // xhandler start with an empty expression stack
2788         if (cur_state->stack_size() != 0) {
2789           // locals are preserved
2790           // stack will be truncated
2791           cur_state = cur_state->copy(ValueStack::ExceptionState, cur_state->bci());
2792         }
2793         if (instruction->exception_state() == nullptr) {
2794           instruction->set_exception_state(cur_state);
2795         }
2796 
2797         // Note: Usually this join must work. However, very
2798         // complicated jsr-ret structures where we don't ret from
2799         // the subroutine can cause the objects on the monitor
2800         // stacks to not match because blocks can be parsed twice.
2801         // The only test case we've seen so far which exhibits this
2802         // problem is caught by the infinite recursion test in
2803         // GraphBuilder::jsr() if the join doesn't work.
2804         if (!entry->try_merge(cur_state, compilation()->has_irreducible_loops())) {
2805           BAILOUT_("error while joining with exception handler, prob. due to complicated jsr/rets", exception_handlers);
2806         }
2807 
2808         // add current state for correct handling of phi functions at begin of xhandler
2809         int phi_operand = entry->add_exception_state(cur_state);
2810 
2811         // add entry to the list of xhandlers of this block
2812         _block->add_exception_handler(entry);
2813 
2814         // add back-edge from xhandler entry to this block
2815         if (!entry->is_predecessor(_block)) {
2816           entry->add_predecessor(_block);
2817         }
2818 
2819         // clone XHandler because phi_operand and scope_count can not be shared
2820         XHandler* new_xhandler = new XHandler(h);
2821         new_xhandler->set_phi_operand(phi_operand);
2822         new_xhandler->set_scope_count(scope_count);
2823         exception_handlers->append(new_xhandler);
2824 
2825         // fill in exception handler subgraph lazily
2826         assert(!entry->is_set(BlockBegin::was_visited_flag), "entry must not be visited yet");
2827         cur_scope_data->add_to_work_list(entry);
2828 
2829         // stop when reaching catchall
2830         if (h->catch_type() == 0) {
2831           return exception_handlers;
2832         }
2833       }
2834     }
2835 
2836     if (exception_handlers->length() == 0) {
2837       // This scope and all callees do not handle exceptions, so the local
2838       // variables of this scope are not needed. However, the scope itself is
2839       // required for a correct exception stack trace -> clear out the locals.
2840       // Stack and locals are invalidated but not truncated in caller state.
2841       if (prev_state != nullptr) {
2842         assert(instruction->exception_state() != nullptr, "missed set?");
2843         ValueStack::Kind exc_kind = ValueStack::empty_exception_kind(true /* caller */);
2844         cur_state = cur_state->copy(exc_kind, cur_state->bci());
2845         // reset caller exception state
2846         prev_state->set_caller_state(cur_state);
2847       } else {
2848         assert(instruction->exception_state() == nullptr, "already set");
2849         // set instruction exception state
2850         // truncate stack
2851         ValueStack::Kind exc_kind = ValueStack::empty_exception_kind();
2852         cur_state = cur_state->copy(exc_kind, cur_state->bci());
2853         instruction->set_exception_state(cur_state);
2854       }
2855     }
2856 
2857     // Set up iteration for next time.
2858     // If parsing a jsr, do not grab exception handlers from the
2859     // parent scopes for this method (already got them, and they
2860     // needed to be cloned)
2861 
2862     while (cur_scope_data->parsing_jsr()) {
2863       cur_scope_data = cur_scope_data->parent();
2864     }
2865 
2866     assert(cur_scope_data->scope() == cur_state->scope(), "scopes do not match");
2867     assert(cur_state->locks_size() == 0 || cur_state->locks_size() == 1, "unlocking must be done in a catchall exception handler");
2868 
2869     prev_state = cur_state;
2870     cur_state = cur_state->caller_state();
2871     cur_scope_data = cur_scope_data->parent();
2872     scope_count++;
2873   } while (cur_scope_data != nullptr);
2874 
2875   return exception_handlers;
2876 }
2877 
2878 
2879 // Helper class for simplifying Phis.
2880 class PhiSimplifier : public BlockClosure {
2881  private:
2882   bool _has_substitutions;
2883   Value simplify(Value v);
2884 
2885  public:
2886   PhiSimplifier(BlockBegin* start) : _has_substitutions(false) {
2887     start->iterate_preorder(this);
2888     if (_has_substitutions) {
2889       SubstitutionResolver sr(start);
2890     }
2891   }
2892   void block_do(BlockBegin* b);
2893   bool has_substitutions() const { return _has_substitutions; }
2894 };
2895 
2896 
2897 Value PhiSimplifier::simplify(Value v) {
2898   Phi* phi = v->as_Phi();
2899 
2900   if (phi == nullptr) {
2901     // no phi function
2902     return v;
2903   } else if (v->has_subst()) {
2904     // already substituted; subst can be phi itself -> simplify
2905     return simplify(v->subst());
2906   } else if (phi->is_set(Phi::cannot_simplify)) {
2907     // already tried to simplify phi before
2908     return phi;
2909   } else if (phi->is_set(Phi::visited)) {
2910     // break cycles in phi functions
2911     return phi;
2912   } else if (phi->type()->is_illegal()) {
2913     // illegal phi functions are ignored anyway
2914     return phi;
2915 
2916   } else {
2917     // mark phi function as processed to break cycles in phi functions
2918     phi->set(Phi::visited);
2919 
2920     // simplify x = [y, x] and x = [y, y] to y
2921     Value subst = nullptr;
2922     int opd_count = phi->operand_count();
2923     for (int i = 0; i < opd_count; i++) {
2924       Value opd = phi->operand_at(i);
2925       assert(opd != nullptr, "Operand must exist!");
2926 
2927       if (opd->type()->is_illegal()) {
2928         // if one operand is illegal, the entire phi function is illegal
2929         phi->make_illegal();
2930         phi->clear(Phi::visited);
2931         return phi;
2932       }
2933 
2934       Value new_opd = simplify(opd);
2935       assert(new_opd != nullptr, "Simplified operand must exist!");
2936 
2937       if (new_opd != phi && new_opd != subst) {
2938         if (subst == nullptr) {
2939           subst = new_opd;
2940         } else {
2941           // no simplification possible
2942           phi->set(Phi::cannot_simplify);
2943           phi->clear(Phi::visited);
2944           return phi;
2945         }
2946       }
2947     }
2948 
2949     // successfully simplified phi function
2950     assert(subst != nullptr, "illegal phi function");
2951     _has_substitutions = true;
2952     phi->clear(Phi::visited);
2953     phi->set_subst(subst);
2954 
2955 #ifndef PRODUCT
2956     if (PrintPhiFunctions) {
2957       tty->print_cr("simplified phi function %c%d to %c%d (Block B%d)", phi->type()->tchar(), phi->id(), subst->type()->tchar(), subst->id(), phi->block()->block_id());
2958     }
2959 #endif
2960 
2961     return subst;
2962   }
2963 }
2964 
2965 
2966 void PhiSimplifier::block_do(BlockBegin* b) {
2967   for_each_phi_fun(b, phi,
2968     simplify(phi);
2969   );
2970 
2971 #ifdef ASSERT
2972   for_each_phi_fun(b, phi,
2973                    assert(phi->operand_count() != 1 || phi->subst() != phi || phi->is_illegal(), "missed trivial simplification");
2974   );
2975 
2976   ValueStack* state = b->state()->caller_state();
2977   for_each_state_value(state, value,
2978     Phi* phi = value->as_Phi();
2979     assert(phi == nullptr || phi->block() != b, "must not have phi function to simplify in caller state");
2980   );
2981 #endif
2982 }
2983 
2984 // This method is called after all blocks are filled with HIR instructions
2985 // It eliminates all Phi functions of the form x = [y, y] and x = [y, x]
2986 void GraphBuilder::eliminate_redundant_phis(BlockBegin* start) {
2987   PhiSimplifier simplifier(start);
2988 }
2989 
2990 
2991 void GraphBuilder::connect_to_end(BlockBegin* beg) {
2992   // setup iteration
2993   kill_all();
2994   _block = beg;
2995   _state = beg->state()->copy_for_parsing();
2996   _last  = beg;
2997   iterate_bytecodes_for_block(beg->bci());
2998 }
2999 
3000 
3001 BlockEnd* GraphBuilder::iterate_bytecodes_for_block(int bci) {
3002 #ifndef PRODUCT
3003   if (PrintIRDuringConstruction) {
3004     tty->cr();
3005     InstructionPrinter ip;
3006     ip.print_instr(_block); tty->cr();
3007     ip.print_stack(_block->state()); tty->cr();
3008     ip.print_inline_level(_block);
3009     ip.print_head();
3010     tty->print_cr("locals size: %d stack size: %d", state()->locals_size(), state()->stack_size());
3011   }
3012 #endif
3013   _skip_block = false;
3014   assert(state() != nullptr, "ValueStack missing!");
3015   CompileLog* log = compilation()->log();
3016   ciBytecodeStream s(method());
3017   s.reset_to_bci(bci);
3018   int prev_bci = bci;
3019   scope_data()->set_stream(&s);
3020   // iterate
3021   Bytecodes::Code code = Bytecodes::_illegal;
3022   bool push_exception = false;
3023 
3024   if (block()->is_set(BlockBegin::exception_entry_flag) && block()->next() == nullptr) {
3025     // first thing in the exception entry block should be the exception object.
3026     push_exception = true;
3027   }
3028 
3029   bool ignore_return = scope_data()->ignore_return();
3030 
3031   while (!bailed_out() && last()->as_BlockEnd() == nullptr &&
3032          (code = stream()->next()) != ciBytecodeStream::EOBC() &&
3033          (block_at(s.cur_bci()) == nullptr || block_at(s.cur_bci()) == block())) {
3034     assert(state()->kind() == ValueStack::Parsing, "invalid state kind");
3035 
3036     if (log != nullptr)
3037       log->set_context("bc code='%d' bci='%d'", (int)code, s.cur_bci());
3038 
3039     // Check for active jsr during OSR compilation
3040     if (compilation()->is_osr_compile()
3041         && scope()->is_top_scope()
3042         && parsing_jsr()
3043         && s.cur_bci() == compilation()->osr_bci()) {
3044       bailout("OSR not supported while a jsr is active");
3045     }
3046 
3047     if (push_exception) {
3048       apush(append(new ExceptionObject()));
3049       push_exception = false;
3050     }
3051 
3052     // handle bytecode
3053     switch (code) {
3054       case Bytecodes::_nop            : /* nothing to do */ break;
3055       case Bytecodes::_aconst_null    : apush(append(new Constant(objectNull            ))); break;
3056       case Bytecodes::_iconst_m1      : ipush(append(new Constant(new IntConstant   (-1)))); break;
3057       case Bytecodes::_iconst_0       : ipush(append(new Constant(intZero               ))); break;
3058       case Bytecodes::_iconst_1       : ipush(append(new Constant(intOne                ))); break;
3059       case Bytecodes::_iconst_2       : ipush(append(new Constant(new IntConstant   ( 2)))); break;
3060       case Bytecodes::_iconst_3       : ipush(append(new Constant(new IntConstant   ( 3)))); break;
3061       case Bytecodes::_iconst_4       : ipush(append(new Constant(new IntConstant   ( 4)))); break;
3062       case Bytecodes::_iconst_5       : ipush(append(new Constant(new IntConstant   ( 5)))); break;
3063       case Bytecodes::_lconst_0       : lpush(append(new Constant(new LongConstant  ( 0)))); break;
3064       case Bytecodes::_lconst_1       : lpush(append(new Constant(new LongConstant  ( 1)))); break;
3065       case Bytecodes::_fconst_0       : fpush(append(new Constant(new FloatConstant ( 0)))); break;
3066       case Bytecodes::_fconst_1       : fpush(append(new Constant(new FloatConstant ( 1)))); break;
3067       case Bytecodes::_fconst_2       : fpush(append(new Constant(new FloatConstant ( 2)))); break;
3068       case Bytecodes::_dconst_0       : dpush(append(new Constant(new DoubleConstant( 0)))); break;
3069       case Bytecodes::_dconst_1       : dpush(append(new Constant(new DoubleConstant( 1)))); break;
3070       case Bytecodes::_bipush         : ipush(append(new Constant(new IntConstant(((signed char*)s.cur_bcp())[1])))); break;
3071       case Bytecodes::_sipush         : ipush(append(new Constant(new IntConstant((short)Bytes::get_Java_u2(s.cur_bcp()+1))))); break;
3072       case Bytecodes::_ldc            : // fall through
3073       case Bytecodes::_ldc_w          : // fall through
3074       case Bytecodes::_ldc2_w         : load_constant(); break;
3075       case Bytecodes::_iload          : load_local(intType     , s.get_index()); break;
3076       case Bytecodes::_lload          : load_local(longType    , s.get_index()); break;
3077       case Bytecodes::_fload          : load_local(floatType   , s.get_index()); break;
3078       case Bytecodes::_dload          : load_local(doubleType  , s.get_index()); break;
3079       case Bytecodes::_aload          : load_local(instanceType, s.get_index()); break;
3080       case Bytecodes::_iload_0        : load_local(intType   , 0); break;
3081       case Bytecodes::_iload_1        : load_local(intType   , 1); break;
3082       case Bytecodes::_iload_2        : load_local(intType   , 2); break;
3083       case Bytecodes::_iload_3        : load_local(intType   , 3); break;
3084       case Bytecodes::_lload_0        : load_local(longType  , 0); break;
3085       case Bytecodes::_lload_1        : load_local(longType  , 1); break;
3086       case Bytecodes::_lload_2        : load_local(longType  , 2); break;
3087       case Bytecodes::_lload_3        : load_local(longType  , 3); break;
3088       case Bytecodes::_fload_0        : load_local(floatType , 0); break;
3089       case Bytecodes::_fload_1        : load_local(floatType , 1); break;
3090       case Bytecodes::_fload_2        : load_local(floatType , 2); break;
3091       case Bytecodes::_fload_3        : load_local(floatType , 3); break;
3092       case Bytecodes::_dload_0        : load_local(doubleType, 0); break;
3093       case Bytecodes::_dload_1        : load_local(doubleType, 1); break;
3094       case Bytecodes::_dload_2        : load_local(doubleType, 2); break;
3095       case Bytecodes::_dload_3        : load_local(doubleType, 3); break;
3096       case Bytecodes::_aload_0        : load_local(objectType, 0); break;
3097       case Bytecodes::_aload_1        : load_local(objectType, 1); break;
3098       case Bytecodes::_aload_2        : load_local(objectType, 2); break;
3099       case Bytecodes::_aload_3        : load_local(objectType, 3); break;
3100       case Bytecodes::_iaload         : load_indexed(T_INT   ); break;
3101       case Bytecodes::_laload         : load_indexed(T_LONG  ); break;
3102       case Bytecodes::_faload         : load_indexed(T_FLOAT ); break;
3103       case Bytecodes::_daload         : load_indexed(T_DOUBLE); break;
3104       case Bytecodes::_aaload         : load_indexed(T_OBJECT); break;
3105       case Bytecodes::_baload         : load_indexed(T_BYTE  ); break;
3106       case Bytecodes::_caload         : load_indexed(T_CHAR  ); break;
3107       case Bytecodes::_saload         : load_indexed(T_SHORT ); break;
3108       case Bytecodes::_istore         : store_local(intType   , s.get_index()); break;
3109       case Bytecodes::_lstore         : store_local(longType  , s.get_index()); break;
3110       case Bytecodes::_fstore         : store_local(floatType , s.get_index()); break;
3111       case Bytecodes::_dstore         : store_local(doubleType, s.get_index()); break;
3112       case Bytecodes::_astore         : store_local(objectType, s.get_index()); break;
3113       case Bytecodes::_istore_0       : store_local(intType   , 0); break;
3114       case Bytecodes::_istore_1       : store_local(intType   , 1); break;
3115       case Bytecodes::_istore_2       : store_local(intType   , 2); break;
3116       case Bytecodes::_istore_3       : store_local(intType   , 3); break;
3117       case Bytecodes::_lstore_0       : store_local(longType  , 0); break;
3118       case Bytecodes::_lstore_1       : store_local(longType  , 1); break;
3119       case Bytecodes::_lstore_2       : store_local(longType  , 2); break;
3120       case Bytecodes::_lstore_3       : store_local(longType  , 3); break;
3121       case Bytecodes::_fstore_0       : store_local(floatType , 0); break;
3122       case Bytecodes::_fstore_1       : store_local(floatType , 1); break;
3123       case Bytecodes::_fstore_2       : store_local(floatType , 2); break;
3124       case Bytecodes::_fstore_3       : store_local(floatType , 3); break;
3125       case Bytecodes::_dstore_0       : store_local(doubleType, 0); break;
3126       case Bytecodes::_dstore_1       : store_local(doubleType, 1); break;
3127       case Bytecodes::_dstore_2       : store_local(doubleType, 2); break;
3128       case Bytecodes::_dstore_3       : store_local(doubleType, 3); break;
3129       case Bytecodes::_astore_0       : store_local(objectType, 0); break;
3130       case Bytecodes::_astore_1       : store_local(objectType, 1); break;
3131       case Bytecodes::_astore_2       : store_local(objectType, 2); break;
3132       case Bytecodes::_astore_3       : store_local(objectType, 3); break;
3133       case Bytecodes::_iastore        : store_indexed(T_INT   ); break;
3134       case Bytecodes::_lastore        : store_indexed(T_LONG  ); break;
3135       case Bytecodes::_fastore        : store_indexed(T_FLOAT ); break;
3136       case Bytecodes::_dastore        : store_indexed(T_DOUBLE); break;
3137       case Bytecodes::_aastore        : store_indexed(T_OBJECT); break;
3138       case Bytecodes::_bastore        : store_indexed(T_BYTE  ); break;
3139       case Bytecodes::_castore        : store_indexed(T_CHAR  ); break;
3140       case Bytecodes::_sastore        : store_indexed(T_SHORT ); break;
3141       case Bytecodes::_pop            : // fall through
3142       case Bytecodes::_pop2           : // fall through
3143       case Bytecodes::_dup            : // fall through
3144       case Bytecodes::_dup_x1         : // fall through
3145       case Bytecodes::_dup_x2         : // fall through
3146       case Bytecodes::_dup2           : // fall through
3147       case Bytecodes::_dup2_x1        : // fall through
3148       case Bytecodes::_dup2_x2        : // fall through
3149       case Bytecodes::_swap           : stack_op(code); break;
3150       case Bytecodes::_iadd           : arithmetic_op(intType   , code); break;
3151       case Bytecodes::_ladd           : arithmetic_op(longType  , code); break;
3152       case Bytecodes::_fadd           : arithmetic_op(floatType , code); break;
3153       case Bytecodes::_dadd           : arithmetic_op(doubleType, code); break;
3154       case Bytecodes::_isub           : arithmetic_op(intType   , code); break;
3155       case Bytecodes::_lsub           : arithmetic_op(longType  , code); break;
3156       case Bytecodes::_fsub           : arithmetic_op(floatType , code); break;
3157       case Bytecodes::_dsub           : arithmetic_op(doubleType, code); break;
3158       case Bytecodes::_imul           : arithmetic_op(intType   , code); break;
3159       case Bytecodes::_lmul           : arithmetic_op(longType  , code); break;
3160       case Bytecodes::_fmul           : arithmetic_op(floatType , code); break;
3161       case Bytecodes::_dmul           : arithmetic_op(doubleType, code); break;
3162       case Bytecodes::_idiv           : arithmetic_op(intType   , code, copy_state_for_exception()); break;
3163       case Bytecodes::_ldiv           : arithmetic_op(longType  , code, copy_state_for_exception()); break;
3164       case Bytecodes::_fdiv           : arithmetic_op(floatType , code); break;
3165       case Bytecodes::_ddiv           : arithmetic_op(doubleType, code); break;
3166       case Bytecodes::_irem           : arithmetic_op(intType   , code, copy_state_for_exception()); break;
3167       case Bytecodes::_lrem           : arithmetic_op(longType  , code, copy_state_for_exception()); break;
3168       case Bytecodes::_frem           : arithmetic_op(floatType , code); break;
3169       case Bytecodes::_drem           : arithmetic_op(doubleType, code); break;
3170       case Bytecodes::_ineg           : negate_op(intType   ); break;
3171       case Bytecodes::_lneg           : negate_op(longType  ); break;
3172       case Bytecodes::_fneg           : negate_op(floatType ); break;
3173       case Bytecodes::_dneg           : negate_op(doubleType); break;
3174       case Bytecodes::_ishl           : shift_op(intType , code); break;
3175       case Bytecodes::_lshl           : shift_op(longType, code); break;
3176       case Bytecodes::_ishr           : shift_op(intType , code); break;
3177       case Bytecodes::_lshr           : shift_op(longType, code); break;
3178       case Bytecodes::_iushr          : shift_op(intType , code); break;
3179       case Bytecodes::_lushr          : shift_op(longType, code); break;
3180       case Bytecodes::_iand           : logic_op(intType , code); break;
3181       case Bytecodes::_land           : logic_op(longType, code); break;
3182       case Bytecodes::_ior            : logic_op(intType , code); break;
3183       case Bytecodes::_lor            : logic_op(longType, code); break;
3184       case Bytecodes::_ixor           : logic_op(intType , code); break;
3185       case Bytecodes::_lxor           : logic_op(longType, code); break;
3186       case Bytecodes::_iinc           : increment(); break;
3187       case Bytecodes::_i2l            : convert(code, T_INT   , T_LONG  ); break;
3188       case Bytecodes::_i2f            : convert(code, T_INT   , T_FLOAT ); break;
3189       case Bytecodes::_i2d            : convert(code, T_INT   , T_DOUBLE); break;
3190       case Bytecodes::_l2i            : convert(code, T_LONG  , T_INT   ); break;
3191       case Bytecodes::_l2f            : convert(code, T_LONG  , T_FLOAT ); break;
3192       case Bytecodes::_l2d            : convert(code, T_LONG  , T_DOUBLE); break;
3193       case Bytecodes::_f2i            : convert(code, T_FLOAT , T_INT   ); break;
3194       case Bytecodes::_f2l            : convert(code, T_FLOAT , T_LONG  ); break;
3195       case Bytecodes::_f2d            : convert(code, T_FLOAT , T_DOUBLE); break;
3196       case Bytecodes::_d2i            : convert(code, T_DOUBLE, T_INT   ); break;
3197       case Bytecodes::_d2l            : convert(code, T_DOUBLE, T_LONG  ); break;
3198       case Bytecodes::_d2f            : convert(code, T_DOUBLE, T_FLOAT ); break;
3199       case Bytecodes::_i2b            : convert(code, T_INT   , T_BYTE  ); break;
3200       case Bytecodes::_i2c            : convert(code, T_INT   , T_CHAR  ); break;
3201       case Bytecodes::_i2s            : convert(code, T_INT   , T_SHORT ); break;
3202       case Bytecodes::_lcmp           : compare_op(longType  , code); break;
3203       case Bytecodes::_fcmpl          : compare_op(floatType , code); break;
3204       case Bytecodes::_fcmpg          : compare_op(floatType , code); break;
3205       case Bytecodes::_dcmpl          : compare_op(doubleType, code); break;
3206       case Bytecodes::_dcmpg          : compare_op(doubleType, code); break;
3207       case Bytecodes::_ifeq           : if_zero(intType   , If::eql); break;
3208       case Bytecodes::_ifne           : if_zero(intType   , If::neq); break;
3209       case Bytecodes::_iflt           : if_zero(intType   , If::lss); break;
3210       case Bytecodes::_ifge           : if_zero(intType   , If::geq); break;
3211       case Bytecodes::_ifgt           : if_zero(intType   , If::gtr); break;
3212       case Bytecodes::_ifle           : if_zero(intType   , If::leq); break;
3213       case Bytecodes::_if_icmpeq      : if_same(intType   , If::eql); break;
3214       case Bytecodes::_if_icmpne      : if_same(intType   , If::neq); break;
3215       case Bytecodes::_if_icmplt      : if_same(intType   , If::lss); break;
3216       case Bytecodes::_if_icmpge      : if_same(intType   , If::geq); break;
3217       case Bytecodes::_if_icmpgt      : if_same(intType   , If::gtr); break;
3218       case Bytecodes::_if_icmple      : if_same(intType   , If::leq); break;
3219       case Bytecodes::_if_acmpeq      : if_same(objectType, If::eql); break;
3220       case Bytecodes::_if_acmpne      : if_same(objectType, If::neq); break;
3221       case Bytecodes::_goto           : _goto(s.cur_bci(), s.get_dest()); break;
3222       case Bytecodes::_jsr            : jsr(s.get_dest()); break;
3223       case Bytecodes::_ret            : ret(s.get_index()); break;
3224       case Bytecodes::_tableswitch    : table_switch(); break;
3225       case Bytecodes::_lookupswitch   : lookup_switch(); break;
3226       case Bytecodes::_ireturn        : method_return(ipop(), ignore_return); break;
3227       case Bytecodes::_lreturn        : method_return(lpop(), ignore_return); break;
3228       case Bytecodes::_freturn        : method_return(fpop(), ignore_return); break;
3229       case Bytecodes::_dreturn        : method_return(dpop(), ignore_return); break;
3230       case Bytecodes::_areturn        : method_return(apop(), ignore_return); break;
3231       case Bytecodes::_return         : method_return(nullptr, ignore_return); break;
3232       case Bytecodes::_getstatic      : // fall through
3233       case Bytecodes::_putstatic      : // fall through
3234       case Bytecodes::_getfield       : // fall through
3235       case Bytecodes::_putfield       : access_field(code); break;
3236       case Bytecodes::_invokevirtual  : // fall through
3237       case Bytecodes::_invokespecial  : // fall through
3238       case Bytecodes::_invokestatic   : // fall through
3239       case Bytecodes::_invokedynamic  : // fall through
3240       case Bytecodes::_invokeinterface: invoke(code); break;
3241       case Bytecodes::_new            : new_instance(s.get_index_u2()); break;
3242       case Bytecodes::_newarray       : new_type_array(); break;
3243       case Bytecodes::_anewarray      : new_object_array(); break;
3244       case Bytecodes::_arraylength    : { ValueStack* state_before = copy_state_for_exception(); ipush(append(new ArrayLength(apop(), state_before))); break; }
3245       case Bytecodes::_athrow         : throw_op(s.cur_bci()); break;
3246       case Bytecodes::_checkcast      : check_cast(s.get_index_u2()); break;
3247       case Bytecodes::_instanceof     : instance_of(s.get_index_u2()); break;
3248       case Bytecodes::_monitorenter   : monitorenter(apop(), s.cur_bci()); break;
3249       case Bytecodes::_monitorexit    : monitorexit (apop(), s.cur_bci()); break;
3250       case Bytecodes::_wide           : ShouldNotReachHere(); break;
3251       case Bytecodes::_multianewarray : new_multi_array(s.cur_bcp()[3]); break;
3252       case Bytecodes::_ifnull         : if_null(objectType, If::eql); break;
3253       case Bytecodes::_ifnonnull      : if_null(objectType, If::neq); break;
3254       case Bytecodes::_goto_w         : _goto(s.cur_bci(), s.get_far_dest()); break;
3255       case Bytecodes::_jsr_w          : jsr(s.get_far_dest()); break;
3256       case Bytecodes::_breakpoint     : BAILOUT_("concurrent setting of breakpoint", nullptr);
3257       default                         : ShouldNotReachHere(); break;
3258     }
3259 
3260     if (log != nullptr)
3261       log->clear_context(); // skip marker if nothing was printed
3262 
3263     // save current bci to setup Goto at the end
3264     prev_bci = s.cur_bci();
3265 
3266   }
3267   CHECK_BAILOUT_(nullptr);
3268   // stop processing of this block (see try_inline_full)
3269   if (_skip_block) {
3270     _skip_block = false;
3271     assert(_last && _last->as_BlockEnd(), "");
3272     return _last->as_BlockEnd();
3273   }
3274   // if there are any, check if last instruction is a BlockEnd instruction
3275   BlockEnd* end = last()->as_BlockEnd();
3276   if (end == nullptr) {
3277     // all blocks must end with a BlockEnd instruction => add a Goto
3278     end = new Goto(block_at(s.cur_bci()), false);
3279     append(end);
3280   }
3281   assert(end == last()->as_BlockEnd(), "inconsistency");
3282 
3283   assert(end->state() != nullptr, "state must already be present");
3284   assert(end->as_Return() == nullptr || end->as_Throw() == nullptr || end->state()->stack_size() == 0, "stack not needed for return and throw");
3285 
3286   // connect to begin & set state
3287   // NOTE that inlining may have changed the block we are parsing
3288   block()->set_end(end);
3289   // propagate state
3290   for (int i = end->number_of_sux() - 1; i >= 0; i--) {
3291     BlockBegin* sux = end->sux_at(i);
3292     assert(sux->is_predecessor(block()), "predecessor missing");
3293     // be careful, bailout if bytecodes are strange
3294     if (!sux->try_merge(end->state(), compilation()->has_irreducible_loops())) BAILOUT_("block join failed", nullptr);
3295     scope_data()->add_to_work_list(end->sux_at(i));
3296   }
3297 
3298   scope_data()->set_stream(nullptr);
3299 
3300   // done
3301   return end;
3302 }
3303 
3304 
3305 void GraphBuilder::iterate_all_blocks(bool start_in_current_block_for_inlining) {
3306   do {
3307     if (start_in_current_block_for_inlining && !bailed_out()) {
3308       iterate_bytecodes_for_block(0);
3309       start_in_current_block_for_inlining = false;
3310     } else {
3311       BlockBegin* b;
3312       while ((b = scope_data()->remove_from_work_list()) != nullptr) {
3313         if (!b->is_set(BlockBegin::was_visited_flag)) {
3314           if (b->is_set(BlockBegin::osr_entry_flag)) {
3315             // we're about to parse the osr entry block, so make sure
3316             // we setup the OSR edge leading into this block so that
3317             // Phis get setup correctly.
3318             setup_osr_entry_block();
3319             // this is no longer the osr entry block, so clear it.
3320             b->clear(BlockBegin::osr_entry_flag);
3321           }
3322           b->set(BlockBegin::was_visited_flag);
3323           connect_to_end(b);
3324         }
3325       }
3326     }
3327   } while (!bailed_out() && !scope_data()->is_work_list_empty());
3328 }
3329 
3330 
3331 bool GraphBuilder::_can_trap      [Bytecodes::number_of_java_codes];
3332 
3333 void GraphBuilder::initialize() {
3334   // the following bytecodes are assumed to potentially
3335   // throw exceptions in compiled code - note that e.g.
3336   // monitorexit & the return bytecodes do not throw
3337   // exceptions since monitor pairing proved that they
3338   // succeed (if monitor pairing succeeded)
3339   Bytecodes::Code can_trap_list[] =
3340     { Bytecodes::_ldc
3341     , Bytecodes::_ldc_w
3342     , Bytecodes::_ldc2_w
3343     , Bytecodes::_iaload
3344     , Bytecodes::_laload
3345     , Bytecodes::_faload
3346     , Bytecodes::_daload
3347     , Bytecodes::_aaload
3348     , Bytecodes::_baload
3349     , Bytecodes::_caload
3350     , Bytecodes::_saload
3351     , Bytecodes::_iastore
3352     , Bytecodes::_lastore
3353     , Bytecodes::_fastore
3354     , Bytecodes::_dastore
3355     , Bytecodes::_aastore
3356     , Bytecodes::_bastore
3357     , Bytecodes::_castore
3358     , Bytecodes::_sastore
3359     , Bytecodes::_idiv
3360     , Bytecodes::_ldiv
3361     , Bytecodes::_irem
3362     , Bytecodes::_lrem
3363     , Bytecodes::_getstatic
3364     , Bytecodes::_putstatic
3365     , Bytecodes::_getfield
3366     , Bytecodes::_putfield
3367     , Bytecodes::_invokevirtual
3368     , Bytecodes::_invokespecial
3369     , Bytecodes::_invokestatic
3370     , Bytecodes::_invokedynamic
3371     , Bytecodes::_invokeinterface
3372     , Bytecodes::_new
3373     , Bytecodes::_newarray
3374     , Bytecodes::_anewarray
3375     , Bytecodes::_arraylength
3376     , Bytecodes::_athrow
3377     , Bytecodes::_checkcast
3378     , Bytecodes::_instanceof
3379     , Bytecodes::_monitorenter
3380     , Bytecodes::_multianewarray
3381     };
3382 
3383   // inititialize trap tables
3384   for (int i = 0; i < Bytecodes::number_of_java_codes; i++) {
3385     _can_trap[i] = false;
3386   }
3387   // set standard trap info
3388   for (uint j = 0; j < ARRAY_SIZE(can_trap_list); j++) {
3389     _can_trap[can_trap_list[j]] = true;
3390   }
3391 }
3392 
3393 
3394 BlockBegin* GraphBuilder::header_block(BlockBegin* entry, BlockBegin::Flag f, ValueStack* state) {
3395   assert(entry->is_set(f), "entry/flag mismatch");
3396   // create header block
3397   BlockBegin* h = new BlockBegin(entry->bci());
3398   h->set_depth_first_number(0);
3399 
3400   Value l = h;
3401   BlockEnd* g = new Goto(entry, false);
3402   l->set_next(g, entry->bci());
3403   h->set_end(g);
3404   h->set(f);
3405   // setup header block end state
3406   ValueStack* s = state->copy(ValueStack::StateAfter, entry->bci()); // can use copy since stack is empty (=> no phis)
3407   assert(s->stack_is_empty(), "must have empty stack at entry point");
3408   g->set_state(s);
3409   return h;
3410 }
3411 
3412 
3413 
3414 BlockBegin* GraphBuilder::setup_start_block(int osr_bci, BlockBegin* std_entry, BlockBegin* osr_entry, ValueStack* state) {
3415   BlockBegin* start = new BlockBegin(0);
3416 
3417   // This code eliminates the empty start block at the beginning of
3418   // each method.  Previously, each method started with the
3419   // start-block created below, and this block was followed by the
3420   // header block that was always empty.  This header block is only
3421   // necessary if std_entry is also a backward branch target because
3422   // then phi functions may be necessary in the header block.  It's
3423   // also necessary when profiling so that there's a single block that
3424   // can increment the counters.
3425   // In addition, with range check elimination, we may need a valid block
3426   // that dominates all the rest to insert range predicates.
3427   BlockBegin* new_header_block;
3428   if (std_entry->number_of_preds() > 0 || is_profiling() || RangeCheckElimination) {
3429     new_header_block = header_block(std_entry, BlockBegin::std_entry_flag, state);
3430   } else {
3431     new_header_block = std_entry;
3432   }
3433 
3434   // setup start block (root for the IR graph)
3435   Base* base =
3436     new Base(
3437       new_header_block,
3438       osr_entry
3439     );
3440   start->set_next(base, 0);
3441   start->set_end(base);
3442   // create & setup state for start block
3443   start->set_state(state->copy(ValueStack::StateAfter, std_entry->bci()));
3444   base->set_state(state->copy(ValueStack::StateAfter, std_entry->bci()));
3445 
3446   if (base->std_entry()->state() == nullptr) {
3447     // setup states for header blocks
3448     base->std_entry()->merge(state, compilation()->has_irreducible_loops());
3449   }
3450 
3451   assert(base->std_entry()->state() != nullptr, "");
3452   return start;
3453 }
3454 
3455 
3456 void GraphBuilder::setup_osr_entry_block() {
3457   assert(compilation()->is_osr_compile(), "only for osrs");
3458 
3459   int osr_bci = compilation()->osr_bci();
3460   ciBytecodeStream s(method());
3461   s.reset_to_bci(osr_bci);
3462   s.next();
3463   scope_data()->set_stream(&s);
3464 
3465   // create a new block to be the osr setup code
3466   _osr_entry = new BlockBegin(osr_bci);
3467   _osr_entry->set(BlockBegin::osr_entry_flag);
3468   _osr_entry->set_depth_first_number(0);
3469   BlockBegin* target = bci2block()->at(osr_bci);
3470   assert(target != nullptr && target->is_set(BlockBegin::osr_entry_flag), "must be there");
3471   // the osr entry has no values for locals
3472   ValueStack* state = target->state()->copy();
3473   _osr_entry->set_state(state);
3474 
3475   kill_all();
3476   _block = _osr_entry;
3477   _state = _osr_entry->state()->copy();
3478   assert(_state->bci() == osr_bci, "mismatch");
3479   _last  = _osr_entry;
3480   Value e = append(new OsrEntry());
3481   e->set_needs_null_check(false);
3482 
3483   // OSR buffer is
3484   //
3485   // locals[nlocals-1..0]
3486   // monitors[number_of_locks-1..0]
3487   //
3488   // locals is a direct copy of the interpreter frame so in the osr buffer
3489   // so first slot in the local array is the last local from the interpreter
3490   // and last slot is local[0] (receiver) from the interpreter
3491   //
3492   // Similarly with locks. The first lock slot in the osr buffer is the nth lock
3493   // from the interpreter frame, the nth lock slot in the osr buffer is 0th lock
3494   // in the interpreter frame (the method lock if a sync method)
3495 
3496   // Initialize monitors in the compiled activation.
3497 
3498   int index;
3499   Value local;
3500 
3501   // find all the locals that the interpreter thinks contain live oops
3502   const ResourceBitMap live_oops = method()->live_local_oops_at_bci(osr_bci);
3503 
3504   // compute the offset into the locals so that we can treat the buffer
3505   // as if the locals were still in the interpreter frame
3506   int locals_offset = BytesPerWord * (method()->max_locals() - 1);
3507   for_each_local_value(state, index, local) {
3508     int offset = locals_offset - (index + local->type()->size() - 1) * BytesPerWord;
3509     Value get;
3510     if (local->type()->is_object_kind() && !live_oops.at(index)) {
3511       // The interpreter thinks this local is dead but the compiler
3512       // doesn't so pretend that the interpreter passed in null.
3513       get = append(new Constant(objectNull));
3514     } else {
3515       Value off_val = append(new Constant(new IntConstant(offset)));
3516       get = append(new UnsafeGet(as_BasicType(local->type()), e,
3517                                  off_val,
3518                                  false/*is_volatile*/,
3519                                  true/*is_raw*/));
3520     }
3521     _state->store_local(index, get);
3522   }
3523 
3524   // the storage for the OSR buffer is freed manually in the LIRGenerator.
3525 
3526   assert(state->caller_state() == nullptr, "should be top scope");
3527   state->clear_locals();
3528   Goto* g = new Goto(target, false);
3529   append(g);
3530   _osr_entry->set_end(g);
3531   target->merge(_osr_entry->end()->state(), compilation()->has_irreducible_loops());
3532 
3533   scope_data()->set_stream(nullptr);
3534 }
3535 
3536 
3537 ValueStack* GraphBuilder::state_at_entry() {
3538   ValueStack* state = new ValueStack(scope(), nullptr);
3539 
3540   // Set up locals for receiver
3541   int idx = 0;
3542   if (!method()->is_static()) {
3543     // we should always see the receiver
3544     state->store_local(idx, new Local(method()->holder(), objectType, idx,
3545              /*receiver*/ true, /*null_free*/ method()->holder()->is_flat_array_klass()));
3546     idx = 1;
3547   }
3548 
3549   // Set up locals for incoming arguments
3550   ciSignature* sig = method()->signature();
3551   for (int i = 0; i < sig->count(); i++) {
3552     ciType* type = sig->type_at(i);
3553     BasicType basic_type = type->basic_type();
3554     // don't allow T_ARRAY to propagate into locals types
3555     if (is_reference_type(basic_type)) basic_type = T_OBJECT;
3556     ValueType* vt = as_ValueType(basic_type);
3557     state->store_local(idx, new Local(type, vt, idx, false, false));
3558     idx += type->size();
3559   }
3560 
3561   // lock synchronized method
3562   if (method()->is_synchronized()) {
3563     state->lock(nullptr);
3564   }
3565 
3566   return state;
3567 }
3568 
3569 
3570 GraphBuilder::GraphBuilder(Compilation* compilation, IRScope* scope)
3571   : _scope_data(nullptr)
3572   , _compilation(compilation)
3573   , _memory(new MemoryBuffer())
3574   , _inline_bailout_msg(nullptr)
3575   , _instruction_count(0)
3576   , _osr_entry(nullptr)
3577   , _pending_field_access(nullptr)
3578   , _pending_load_indexed(nullptr)
3579 {
3580   int osr_bci = compilation->osr_bci();
3581 
3582   // determine entry points and bci2block mapping
3583   BlockListBuilder blm(compilation, scope, osr_bci);
3584   CHECK_BAILOUT();
3585 
3586   BlockList* bci2block = blm.bci2block();
3587   BlockBegin* start_block = bci2block->at(0);
3588 
3589   push_root_scope(scope, bci2block, start_block);
3590 
3591   // setup state for std entry
3592   _initial_state = state_at_entry();
3593   start_block->merge(_initial_state, compilation->has_irreducible_loops());
3594 
3595   // End nulls still exist here
3596 
3597   // complete graph
3598   _vmap        = new ValueMap();
3599   switch (scope->method()->intrinsic_id()) {
3600   case vmIntrinsics::_dabs          : // fall through
3601   case vmIntrinsics::_dsqrt         : // fall through
3602   case vmIntrinsics::_dsqrt_strict  : // fall through
3603   case vmIntrinsics::_dsin          : // fall through
3604   case vmIntrinsics::_dcos          : // fall through
3605   case vmIntrinsics::_dtan          : // fall through
3606   case vmIntrinsics::_dlog          : // fall through
3607   case vmIntrinsics::_dlog10        : // fall through
3608   case vmIntrinsics::_dexp          : // fall through
3609   case vmIntrinsics::_dpow          : // fall through
3610     {
3611       // Compiles where the root method is an intrinsic need a special
3612       // compilation environment because the bytecodes for the method
3613       // shouldn't be parsed during the compilation, only the special
3614       // Intrinsic node should be emitted.  If this isn't done the
3615       // code for the inlined version will be different than the root
3616       // compiled version which could lead to monotonicity problems on
3617       // intel.
3618       if (CheckIntrinsics && !scope->method()->intrinsic_candidate()) {
3619         BAILOUT("failed to inline intrinsic, method not annotated");
3620       }
3621 
3622       // Set up a stream so that appending instructions works properly.
3623       ciBytecodeStream s(scope->method());
3624       s.reset_to_bci(0);
3625       scope_data()->set_stream(&s);
3626       s.next();
3627 
3628       // setup the initial block state
3629       _block = start_block;
3630       _state = start_block->state()->copy_for_parsing();
3631       _last  = start_block;
3632       load_local(doubleType, 0);
3633       if (scope->method()->intrinsic_id() == vmIntrinsics::_dpow) {
3634         load_local(doubleType, 2);
3635       }
3636 
3637       // Emit the intrinsic node.
3638       bool result = try_inline_intrinsics(scope->method());
3639       if (!result) BAILOUT("failed to inline intrinsic");
3640       method_return(dpop());
3641 
3642       // connect the begin and end blocks and we're all done.
3643       BlockEnd* end = last()->as_BlockEnd();
3644       block()->set_end(end);
3645       break;
3646     }
3647 
3648   case vmIntrinsics::_Reference_get:
3649     {
3650       {
3651         // With java.lang.ref.reference.get() we must go through the
3652         // intrinsic - when G1 is enabled - even when get() is the root
3653         // method of the compile so that, if necessary, the value in
3654         // the referent field of the reference object gets recorded by
3655         // the pre-barrier code.
3656         // Specifically, if G1 is enabled, the value in the referent
3657         // field is recorded by the G1 SATB pre barrier. This will
3658         // result in the referent being marked live and the reference
3659         // object removed from the list of discovered references during
3660         // reference processing.
3661         if (CheckIntrinsics && !scope->method()->intrinsic_candidate()) {
3662           BAILOUT("failed to inline intrinsic, method not annotated");
3663         }
3664 
3665         // Also we need intrinsic to prevent commoning reads from this field
3666         // across safepoint since GC can change its value.
3667 
3668         // Set up a stream so that appending instructions works properly.
3669         ciBytecodeStream s(scope->method());
3670         s.reset_to_bci(0);
3671         scope_data()->set_stream(&s);
3672         s.next();
3673 
3674         // setup the initial block state
3675         _block = start_block;
3676         _state = start_block->state()->copy_for_parsing();
3677         _last  = start_block;
3678         load_local(objectType, 0);
3679 
3680         // Emit the intrinsic node.
3681         bool result = try_inline_intrinsics(scope->method());
3682         if (!result) BAILOUT("failed to inline intrinsic");
3683         method_return(apop());
3684 
3685         // connect the begin and end blocks and we're all done.
3686         BlockEnd* end = last()->as_BlockEnd();
3687         block()->set_end(end);
3688         break;
3689       }
3690       // Otherwise, fall thru
3691     }
3692 
3693   default:
3694     scope_data()->add_to_work_list(start_block);
3695     iterate_all_blocks();
3696     break;
3697   }
3698   CHECK_BAILOUT();
3699 
3700 # ifdef ASSERT
3701   // For all blocks reachable from start_block: _end must be non-null
3702   {
3703     BlockList processed;
3704     BlockList to_go;
3705     to_go.append(start_block);
3706     while(to_go.length() > 0) {
3707       BlockBegin* current = to_go.pop();
3708       assert(current != nullptr, "Should not happen.");
3709       assert(current->end() != nullptr, "All blocks reachable from start_block should have end() != nullptr.");
3710       processed.append(current);
3711       for(int i = 0; i < current->number_of_sux(); i++) {
3712         BlockBegin* s = current->sux_at(i);
3713         if (!processed.contains(s)) {
3714           to_go.append(s);
3715         }
3716       }
3717     }
3718   }
3719 #endif // ASSERT
3720 
3721   _start = setup_start_block(osr_bci, start_block, _osr_entry, _initial_state);
3722 
3723   eliminate_redundant_phis(_start);
3724 
3725   NOT_PRODUCT(if (PrintValueNumbering && Verbose) print_stats());
3726   // for osr compile, bailout if some requirements are not fulfilled
3727   if (osr_bci != -1) {
3728     BlockBegin* osr_block = blm.bci2block()->at(osr_bci);
3729     if (!osr_block->is_set(BlockBegin::was_visited_flag)) {
3730       BAILOUT("osr entry must have been visited for osr compile");
3731     }
3732 
3733     // check if osr entry point has empty stack - we cannot handle non-empty stacks at osr entry points
3734     if (!osr_block->state()->stack_is_empty()) {
3735       BAILOUT("stack not empty at OSR entry point");
3736     }
3737   }
3738 #ifndef PRODUCT
3739   if (PrintCompilation && Verbose) tty->print_cr("Created %d Instructions", _instruction_count);
3740 #endif
3741 }
3742 
3743 
3744 ValueStack* GraphBuilder::copy_state_before() {
3745   return copy_state_before_with_bci(bci());
3746 }
3747 
3748 ValueStack* GraphBuilder::copy_state_exhandling() {
3749   return copy_state_exhandling_with_bci(bci());
3750 }
3751 
3752 ValueStack* GraphBuilder::copy_state_for_exception() {
3753   return copy_state_for_exception_with_bci(bci());
3754 }
3755 
3756 ValueStack* GraphBuilder::copy_state_before_with_bci(int bci) {
3757   return state()->copy(ValueStack::StateBefore, bci);
3758 }
3759 
3760 ValueStack* GraphBuilder::copy_state_exhandling_with_bci(int bci) {
3761   if (!has_handler()) return nullptr;
3762   return state()->copy(ValueStack::StateBefore, bci);
3763 }
3764 
3765 ValueStack* GraphBuilder::copy_state_for_exception_with_bci(int bci) {
3766   ValueStack* s = copy_state_exhandling_with_bci(bci);
3767   if (s == nullptr) {
3768     // no handler, no need to retain locals
3769     ValueStack::Kind exc_kind = ValueStack::empty_exception_kind();
3770     s = state()->copy(exc_kind, bci);
3771   }
3772   return s;
3773 }
3774 
3775 int GraphBuilder::recursive_inline_level(ciMethod* cur_callee) const {
3776   int recur_level = 0;
3777   for (IRScope* s = scope(); s != nullptr; s = s->caller()) {
3778     if (s->method() == cur_callee) {
3779       ++recur_level;
3780     }
3781   }
3782   return recur_level;
3783 }
3784 
3785 static void set_flags_for_inlined_callee(Compilation* compilation, ciMethod* callee) {
3786   if (callee->has_reserved_stack_access()) {
3787     compilation->set_has_reserved_stack_access(true);
3788   }
3789   if (callee->is_synchronized() || callee->has_monitor_bytecodes()) {
3790     compilation->set_has_monitors(true);
3791   }
3792 }
3793 
3794 bool GraphBuilder::try_inline(ciMethod* callee, bool holder_known, bool ignore_return, Bytecodes::Code bc, Value receiver) {
3795   const char* msg = nullptr;
3796 
3797   // clear out any existing inline bailout condition
3798   clear_inline_bailout();
3799 
3800   // exclude methods we don't want to inline
3801   msg = should_not_inline(callee);
3802   if (msg != nullptr) {
3803     print_inlining(callee, msg, /*success*/ false);
3804     return false;
3805   }
3806 
3807   // method handle invokes
3808   if (callee->is_method_handle_intrinsic()) {
3809     if (try_method_handle_inline(callee, ignore_return)) {
3810       set_flags_for_inlined_callee(compilation(), callee);
3811       return true;
3812     }
3813     return false;
3814   }
3815 
3816   // handle intrinsics
3817   if (callee->intrinsic_id() != vmIntrinsics::_none &&
3818       callee->check_intrinsic_candidate()) {
3819     if (try_inline_intrinsics(callee, ignore_return)) {
3820       print_inlining(callee, "intrinsic");
3821       set_flags_for_inlined_callee(compilation(), callee);
3822       return true;
3823     }
3824     // try normal inlining
3825   }
3826 
3827   // certain methods cannot be parsed at all
3828   msg = check_can_parse(callee);
3829   if (msg != nullptr) {
3830     print_inlining(callee, msg, /*success*/ false);
3831     return false;
3832   }
3833 
3834   // If bytecode not set use the current one.
3835   if (bc == Bytecodes::_illegal) {
3836     bc = code();
3837   }
3838   if (try_inline_full(callee, holder_known, ignore_return, bc, receiver)) {
3839     set_flags_for_inlined_callee(compilation(), callee);
3840     return true;
3841   }
3842 
3843   // Entire compilation could fail during try_inline_full call.
3844   // In that case printing inlining decision info is useless.
3845   if (!bailed_out())
3846     print_inlining(callee, _inline_bailout_msg, /*success*/ false);
3847 
3848   return false;
3849 }
3850 
3851 
3852 const char* GraphBuilder::check_can_parse(ciMethod* callee) const {
3853   // Certain methods cannot be parsed at all:
3854   if ( callee->is_native())            return "native method";
3855   if ( callee->is_abstract())          return "abstract method";
3856   if (!callee->can_be_parsed())        return "cannot be parsed";
3857   return nullptr;
3858 }
3859 
3860 // negative filter: should callee NOT be inlined?  returns null, ok to inline, or rejection msg
3861 const char* GraphBuilder::should_not_inline(ciMethod* callee) const {
3862   if ( compilation()->directive()->should_not_inline(callee)) return "disallowed by CompileCommand";
3863   if ( callee->dont_inline())          return "don't inline by annotation";
3864   return nullptr;
3865 }
3866 
3867 void GraphBuilder::build_graph_for_intrinsic(ciMethod* callee, bool ignore_return) {
3868   vmIntrinsics::ID id = callee->intrinsic_id();
3869   assert(id != vmIntrinsics::_none, "must be a VM intrinsic");
3870 
3871   // Some intrinsics need special IR nodes.
3872   switch(id) {
3873   case vmIntrinsics::_getReference           : append_unsafe_get(callee, T_OBJECT,  false); return;
3874   case vmIntrinsics::_getBoolean             : append_unsafe_get(callee, T_BOOLEAN, false); return;
3875   case vmIntrinsics::_getByte                : append_unsafe_get(callee, T_BYTE,    false); return;
3876   case vmIntrinsics::_getShort               : append_unsafe_get(callee, T_SHORT,   false); return;
3877   case vmIntrinsics::_getChar                : append_unsafe_get(callee, T_CHAR,    false); return;
3878   case vmIntrinsics::_getInt                 : append_unsafe_get(callee, T_INT,     false); return;
3879   case vmIntrinsics::_getLong                : append_unsafe_get(callee, T_LONG,    false); return;
3880   case vmIntrinsics::_getFloat               : append_unsafe_get(callee, T_FLOAT,   false); return;
3881   case vmIntrinsics::_getDouble              : append_unsafe_get(callee, T_DOUBLE,  false); return;
3882   case vmIntrinsics::_putReference           : append_unsafe_put(callee, T_OBJECT,  false); return;
3883   case vmIntrinsics::_putBoolean             : append_unsafe_put(callee, T_BOOLEAN, false); return;
3884   case vmIntrinsics::_putByte                : append_unsafe_put(callee, T_BYTE,    false); return;
3885   case vmIntrinsics::_putShort               : append_unsafe_put(callee, T_SHORT,   false); return;
3886   case vmIntrinsics::_putChar                : append_unsafe_put(callee, T_CHAR,    false); return;
3887   case vmIntrinsics::_putInt                 : append_unsafe_put(callee, T_INT,     false); return;
3888   case vmIntrinsics::_putLong                : append_unsafe_put(callee, T_LONG,    false); return;
3889   case vmIntrinsics::_putFloat               : append_unsafe_put(callee, T_FLOAT,   false); return;
3890   case vmIntrinsics::_putDouble              : append_unsafe_put(callee, T_DOUBLE,  false); return;
3891   case vmIntrinsics::_getShortUnaligned      : append_unsafe_get(callee, T_SHORT,   false); return;
3892   case vmIntrinsics::_getCharUnaligned       : append_unsafe_get(callee, T_CHAR,    false); return;
3893   case vmIntrinsics::_getIntUnaligned        : append_unsafe_get(callee, T_INT,     false); return;
3894   case vmIntrinsics::_getLongUnaligned       : append_unsafe_get(callee, T_LONG,    false); return;
3895   case vmIntrinsics::_putShortUnaligned      : append_unsafe_put(callee, T_SHORT,   false); return;
3896   case vmIntrinsics::_putCharUnaligned       : append_unsafe_put(callee, T_CHAR,    false); return;
3897   case vmIntrinsics::_putIntUnaligned        : append_unsafe_put(callee, T_INT,     false); return;
3898   case vmIntrinsics::_putLongUnaligned       : append_unsafe_put(callee, T_LONG,    false); return;
3899   case vmIntrinsics::_getReferenceVolatile   : append_unsafe_get(callee, T_OBJECT,  true); return;
3900   case vmIntrinsics::_getBooleanVolatile     : append_unsafe_get(callee, T_BOOLEAN, true); return;
3901   case vmIntrinsics::_getByteVolatile        : append_unsafe_get(callee, T_BYTE,    true); return;
3902   case vmIntrinsics::_getShortVolatile       : append_unsafe_get(callee, T_SHORT,   true); return;
3903   case vmIntrinsics::_getCharVolatile        : append_unsafe_get(callee, T_CHAR,    true); return;
3904   case vmIntrinsics::_getIntVolatile         : append_unsafe_get(callee, T_INT,     true); return;
3905   case vmIntrinsics::_getLongVolatile        : append_unsafe_get(callee, T_LONG,    true); return;
3906   case vmIntrinsics::_getFloatVolatile       : append_unsafe_get(callee, T_FLOAT,   true); return;
3907   case vmIntrinsics::_getDoubleVolatile      : append_unsafe_get(callee, T_DOUBLE,  true); return;
3908   case vmIntrinsics::_putReferenceVolatile   : append_unsafe_put(callee, T_OBJECT,  true); return;
3909   case vmIntrinsics::_putBooleanVolatile     : append_unsafe_put(callee, T_BOOLEAN, true); return;
3910   case vmIntrinsics::_putByteVolatile        : append_unsafe_put(callee, T_BYTE,    true); return;
3911   case vmIntrinsics::_putShortVolatile       : append_unsafe_put(callee, T_SHORT,   true); return;
3912   case vmIntrinsics::_putCharVolatile        : append_unsafe_put(callee, T_CHAR,    true); return;
3913   case vmIntrinsics::_putIntVolatile         : append_unsafe_put(callee, T_INT,     true); return;
3914   case vmIntrinsics::_putLongVolatile        : append_unsafe_put(callee, T_LONG,    true); return;
3915   case vmIntrinsics::_putFloatVolatile       : append_unsafe_put(callee, T_FLOAT,   true); return;
3916   case vmIntrinsics::_putDoubleVolatile      : append_unsafe_put(callee, T_DOUBLE,  true); return;
3917   case vmIntrinsics::_compareAndSetLong:
3918   case vmIntrinsics::_compareAndSetInt:
3919   case vmIntrinsics::_compareAndSetReference : append_unsafe_CAS(callee); return;
3920   case vmIntrinsics::_getAndAddInt:
3921   case vmIntrinsics::_getAndAddLong          : append_unsafe_get_and_set(callee, true); return;
3922   case vmIntrinsics::_getAndSetInt           :
3923   case vmIntrinsics::_getAndSetLong          :
3924   case vmIntrinsics::_getAndSetReference     : append_unsafe_get_and_set(callee, false); return;
3925   case vmIntrinsics::_getCharStringU         : append_char_access(callee, false); return;
3926   case vmIntrinsics::_putCharStringU         : append_char_access(callee, true); return;
3927   default:
3928     break;
3929   }
3930 
3931   // create intrinsic node
3932   const bool has_receiver = !callee->is_static();
3933   ValueType* result_type = as_ValueType(callee->return_type());
3934   ValueStack* state_before = copy_state_for_exception();
3935 
3936   Values* args = state()->pop_arguments(callee->arg_size());
3937 
3938   if (is_profiling()) {
3939     // Don't profile in the special case where the root method
3940     // is the intrinsic
3941     if (callee != method()) {
3942       // Note that we'd collect profile data in this method if we wanted it.
3943       compilation()->set_would_profile(true);
3944       if (profile_calls()) {
3945         Value recv = nullptr;
3946         if (has_receiver) {
3947           recv = args->at(0);
3948           null_check(recv);
3949         }
3950         profile_call(callee, recv, nullptr, collect_args_for_profiling(args, callee, true), true);
3951       }
3952     }
3953   }
3954 
3955   Intrinsic* result = new Intrinsic(result_type, callee->intrinsic_id(),
3956                                     args, has_receiver, state_before,
3957                                     vmIntrinsics::preserves_state(id),
3958                                     vmIntrinsics::can_trap(id));
3959   // append instruction & push result
3960   Value value = append_split(result);
3961   if (result_type != voidType && !ignore_return) {
3962     push(result_type, value);
3963   }
3964 
3965   if (callee != method() && profile_return() && result_type->is_object_kind()) {
3966     profile_return_type(result, callee);
3967   }
3968 }
3969 
3970 bool GraphBuilder::try_inline_intrinsics(ciMethod* callee, bool ignore_return) {
3971   // For calling is_intrinsic_available we need to transition to
3972   // the '_thread_in_vm' state because is_intrinsic_available()
3973   // accesses critical VM-internal data.
3974   bool is_available = false;
3975   {
3976     VM_ENTRY_MARK;
3977     methodHandle mh(THREAD, callee->get_Method());
3978     is_available = _compilation->compiler()->is_intrinsic_available(mh, _compilation->directive());
3979   }
3980 
3981   if (!is_available) {
3982     if (!InlineNatives) {
3983       // Return false and also set message that the inlining of
3984       // intrinsics has been disabled in general.
3985       INLINE_BAILOUT("intrinsic method inlining disabled");
3986     } else {
3987       return false;
3988     }
3989   }
3990   build_graph_for_intrinsic(callee, ignore_return);
3991   return true;
3992 }
3993 
3994 
3995 bool GraphBuilder::try_inline_jsr(int jsr_dest_bci) {
3996   // Introduce a new callee continuation point - all Ret instructions
3997   // will be replaced with Gotos to this point.
3998   BlockBegin* cont = block_at(next_bci());
3999   assert(cont != nullptr, "continuation must exist (BlockListBuilder starts a new block after a jsr");
4000 
4001   // Note: can not assign state to continuation yet, as we have to
4002   // pick up the state from the Ret instructions.
4003 
4004   // Push callee scope
4005   push_scope_for_jsr(cont, jsr_dest_bci);
4006 
4007   // Temporarily set up bytecode stream so we can append instructions
4008   // (only using the bci of this stream)
4009   scope_data()->set_stream(scope_data()->parent()->stream());
4010 
4011   BlockBegin* jsr_start_block = block_at(jsr_dest_bci);
4012   assert(jsr_start_block != nullptr, "jsr start block must exist");
4013   assert(!jsr_start_block->is_set(BlockBegin::was_visited_flag), "should not have visited jsr yet");
4014   Goto* goto_sub = new Goto(jsr_start_block, false);
4015   // Must copy state to avoid wrong sharing when parsing bytecodes
4016   assert(jsr_start_block->state() == nullptr, "should have fresh jsr starting block");
4017   jsr_start_block->set_state(copy_state_before_with_bci(jsr_dest_bci));
4018   append(goto_sub);
4019   _block->set_end(goto_sub);
4020   _last = _block = jsr_start_block;
4021 
4022   // Clear out bytecode stream
4023   scope_data()->set_stream(nullptr);
4024 
4025   scope_data()->add_to_work_list(jsr_start_block);
4026 
4027   // Ready to resume parsing in subroutine
4028   iterate_all_blocks();
4029 
4030   // If we bailed out during parsing, return immediately (this is bad news)
4031   CHECK_BAILOUT_(false);
4032 
4033   // Detect whether the continuation can actually be reached. If not,
4034   // it has not had state set by the join() operations in
4035   // iterate_bytecodes_for_block()/ret() and we should not touch the
4036   // iteration state. The calling activation of
4037   // iterate_bytecodes_for_block will then complete normally.
4038   if (cont->state() != nullptr) {
4039     if (!cont->is_set(BlockBegin::was_visited_flag)) {
4040       // add continuation to work list instead of parsing it immediately
4041       scope_data()->parent()->add_to_work_list(cont);
4042     }
4043   }
4044 
4045   assert(jsr_continuation() == cont, "continuation must not have changed");
4046   assert(!jsr_continuation()->is_set(BlockBegin::was_visited_flag) ||
4047          jsr_continuation()->is_set(BlockBegin::parser_loop_header_flag),
4048          "continuation can only be visited in case of backward branches");
4049   assert(_last && _last->as_BlockEnd(), "block must have end");
4050 
4051   // continuation is in work list, so end iteration of current block
4052   _skip_block = true;
4053   pop_scope_for_jsr();
4054 
4055   return true;
4056 }
4057 
4058 
4059 // Inline the entry of a synchronized method as a monitor enter and
4060 // register the exception handler which releases the monitor if an
4061 // exception is thrown within the callee. Note that the monitor enter
4062 // cannot throw an exception itself, because the receiver is
4063 // guaranteed to be non-null by the explicit null check at the
4064 // beginning of inlining.
4065 void GraphBuilder::inline_sync_entry(Value lock, BlockBegin* sync_handler) {
4066   assert(lock != nullptr && sync_handler != nullptr, "lock or handler missing");
4067 
4068   monitorenter(lock, SynchronizationEntryBCI);
4069   assert(_last->as_MonitorEnter() != nullptr, "monitor enter expected");
4070   _last->set_needs_null_check(false);
4071 
4072   sync_handler->set(BlockBegin::exception_entry_flag);
4073   sync_handler->set(BlockBegin::is_on_work_list_flag);
4074 
4075   ciExceptionHandler* desc = new ciExceptionHandler(method()->holder(), 0, method()->code_size(), -1, 0);
4076   XHandler* h = new XHandler(desc);
4077   h->set_entry_block(sync_handler);
4078   scope_data()->xhandlers()->append(h);
4079   scope_data()->set_has_handler();
4080 }
4081 
4082 
4083 // If an exception is thrown and not handled within an inlined
4084 // synchronized method, the monitor must be released before the
4085 // exception is rethrown in the outer scope. Generate the appropriate
4086 // instructions here.
4087 void GraphBuilder::fill_sync_handler(Value lock, BlockBegin* sync_handler, bool default_handler) {
4088   BlockBegin* orig_block = _block;
4089   ValueStack* orig_state = _state;
4090   Instruction* orig_last = _last;
4091   _last = _block = sync_handler;
4092   _state = sync_handler->state()->copy();
4093 
4094   assert(sync_handler != nullptr, "handler missing");
4095   assert(!sync_handler->is_set(BlockBegin::was_visited_flag), "is visited here");
4096 
4097   assert(lock != nullptr || default_handler, "lock or handler missing");
4098 
4099   XHandler* h = scope_data()->xhandlers()->remove_last();
4100   assert(h->entry_block() == sync_handler, "corrupt list of handlers");
4101 
4102   block()->set(BlockBegin::was_visited_flag);
4103   Value exception = append_with_bci(new ExceptionObject(), SynchronizationEntryBCI);
4104   assert(exception->is_pinned(), "must be");
4105 
4106   int bci = SynchronizationEntryBCI;
4107   if (compilation()->env()->dtrace_method_probes()) {
4108     // Report exit from inline methods.  We don't have a stream here
4109     // so pass an explicit bci of SynchronizationEntryBCI.
4110     Values* args = new Values(1);
4111     args->push(append_with_bci(new Constant(new MethodConstant(method())), bci));
4112     append_with_bci(new RuntimeCall(voidType, "dtrace_method_exit", CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit), args), bci);
4113   }
4114 
4115   if (lock) {
4116     assert(state()->locks_size() > 0 && state()->lock_at(state()->locks_size() - 1) == lock, "lock is missing");
4117     if (!lock->is_linked()) {
4118       lock = append_with_bci(lock, bci);
4119     }
4120 
4121     // exit the monitor in the context of the synchronized method
4122     monitorexit(lock, bci);
4123 
4124     // exit the context of the synchronized method
4125     if (!default_handler) {
4126       pop_scope();
4127       bci = _state->caller_state()->bci();
4128       _state = _state->caller_state()->copy_for_parsing();
4129     }
4130   }
4131 
4132   // perform the throw as if at the call site
4133   apush(exception);
4134   throw_op(bci);
4135 
4136   BlockEnd* end = last()->as_BlockEnd();
4137   block()->set_end(end);
4138 
4139   _block = orig_block;
4140   _state = orig_state;
4141   _last = orig_last;
4142 }
4143 
4144 
4145 bool GraphBuilder::try_inline_full(ciMethod* callee, bool holder_known, bool ignore_return, Bytecodes::Code bc, Value receiver) {
4146   assert(!callee->is_native(), "callee must not be native");
4147   if (CompilationPolicy::should_not_inline(compilation()->env(), callee)) {
4148     INLINE_BAILOUT("inlining prohibited by policy");
4149   }
4150   // first perform tests of things it's not possible to inline
4151   if (callee->has_exception_handlers() &&
4152       !InlineMethodsWithExceptionHandlers) INLINE_BAILOUT("callee has exception handlers");
4153   if (callee->is_synchronized() &&
4154       !InlineSynchronizedMethods         ) INLINE_BAILOUT("callee is synchronized");
4155   if (!callee->holder()->is_linked())      INLINE_BAILOUT("callee's klass not linked yet");
4156   if (bc == Bytecodes::_invokestatic &&
4157       !callee->holder()->is_initialized()) INLINE_BAILOUT("callee's klass not initialized yet");
4158   if (!callee->has_balanced_monitors())    INLINE_BAILOUT("callee's monitors do not match");
4159 
4160   // Proper inlining of methods with jsrs requires a little more work.
4161   if (callee->has_jsrs()                 ) INLINE_BAILOUT("jsrs not handled properly by inliner yet");
4162 
4163   if (is_profiling() && !callee->ensure_method_data()) {
4164     INLINE_BAILOUT("mdo allocation failed");
4165   }
4166 
4167   const bool is_invokedynamic = (bc == Bytecodes::_invokedynamic);
4168   const bool has_receiver = (bc != Bytecodes::_invokestatic && !is_invokedynamic);
4169 
4170   const int args_base = state()->stack_size() - callee->arg_size();
4171   assert(args_base >= 0, "stack underflow during inlining");
4172 
4173   Value recv = nullptr;
4174   if (has_receiver) {
4175     assert(!callee->is_static(), "callee must not be static");
4176     assert(callee->arg_size() > 0, "must have at least a receiver");
4177 
4178     recv = state()->stack_at(args_base);
4179     if (recv->is_null_obj()) {
4180       INLINE_BAILOUT("receiver is always null");
4181     }
4182   }
4183 
4184   // now perform tests that are based on flag settings
4185   bool inlinee_by_directive = compilation()->directive()->should_inline(callee);
4186   if (callee->force_inline() || inlinee_by_directive) {
4187     if (inline_level() > MaxForceInlineLevel                      ) INLINE_BAILOUT("MaxForceInlineLevel");
4188     if (recursive_inline_level(callee) > C1MaxRecursiveInlineLevel) INLINE_BAILOUT("recursive inlining too deep");
4189 
4190     const char* msg = "";
4191     if (callee->force_inline())  msg = "force inline by annotation";
4192     if (inlinee_by_directive)    msg = "force inline by CompileCommand";
4193     print_inlining(callee, msg);
4194   } else {
4195     // use heuristic controls on inlining
4196     if (inline_level() > C1MaxInlineLevel                       ) INLINE_BAILOUT("inlining too deep");
4197     int callee_recursive_level = recursive_inline_level(callee);
4198     if (callee_recursive_level > C1MaxRecursiveInlineLevel      ) INLINE_BAILOUT("recursive inlining too deep");
4199     if (callee->code_size_for_inlining() > max_inline_size()    ) INLINE_BAILOUT("callee is too large");
4200     // Additional condition to limit stack usage for non-recursive calls.
4201     if ((callee_recursive_level == 0) &&
4202         (callee->max_stack() + callee->max_locals() - callee->size_of_parameters() > C1InlineStackLimit)) {
4203       INLINE_BAILOUT("callee uses too much stack");
4204     }
4205 
4206     // don't inline throwable methods unless the inlining tree is rooted in a throwable class
4207     if (callee->name() == ciSymbols::object_initializer_name() &&
4208         callee->holder()->is_subclass_of(ciEnv::current()->Throwable_klass())) {
4209       // Throwable constructor call
4210       IRScope* top = scope();
4211       while (top->caller() != nullptr) {
4212         top = top->caller();
4213       }
4214       if (!top->method()->holder()->is_subclass_of(ciEnv::current()->Throwable_klass())) {
4215         INLINE_BAILOUT("don't inline Throwable constructors");
4216       }
4217     }
4218 
4219     if (compilation()->env()->num_inlined_bytecodes() > DesiredMethodLimit) {
4220       INLINE_BAILOUT("total inlining greater than DesiredMethodLimit");
4221     }
4222     // printing
4223     print_inlining(callee, "inline", /*success*/ true);
4224   }
4225 
4226   assert(bc != Bytecodes::_invokestatic || callee->holder()->is_initialized(), "required");
4227 
4228   // NOTE: Bailouts from this point on, which occur at the
4229   // GraphBuilder level, do not cause bailout just of the inlining but
4230   // in fact of the entire compilation.
4231 
4232   BlockBegin* orig_block = block();
4233 
4234   // Insert null check if necessary
4235   if (has_receiver) {
4236     // note: null check must happen even if first instruction of callee does
4237     //       an implicit null check since the callee is in a different scope
4238     //       and we must make sure exception handling does the right thing
4239     null_check(recv);
4240   }
4241 
4242   if (is_profiling()) {
4243     // Note that we'd collect profile data in this method if we wanted it.
4244     // this may be redundant here...
4245     compilation()->set_would_profile(true);
4246 
4247     if (profile_calls()) {
4248       int start = 0;
4249       Values* obj_args = args_list_for_profiling(callee, start, has_receiver);
4250       if (obj_args != nullptr) {
4251         int s = obj_args->capacity();
4252         // if called through method handle invoke, some arguments may have been popped
4253         for (int i = args_base+start, j = 0; j < obj_args->capacity() && i < state()->stack_size(); ) {
4254           Value v = state()->stack_at_inc(i);
4255           if (v->type()->is_object_kind()) {
4256             obj_args->push(v);
4257             j++;
4258           }
4259         }
4260         check_args_for_profiling(obj_args, s);
4261       }
4262       profile_call(callee, recv, holder_known ? callee->holder() : nullptr, obj_args, true);
4263     }
4264   }
4265 
4266   // Introduce a new callee continuation point - if the callee has
4267   // more than one return instruction or the return does not allow
4268   // fall-through of control flow, all return instructions of the
4269   // callee will need to be replaced by Goto's pointing to this
4270   // continuation point.
4271   BlockBegin* cont = block_at(next_bci());
4272   bool continuation_existed = true;
4273   if (cont == nullptr) {
4274     cont = new BlockBegin(next_bci());
4275     // low number so that continuation gets parsed as early as possible
4276     cont->set_depth_first_number(0);
4277     if (PrintInitialBlockList) {
4278       tty->print_cr("CFG: created block %d (bci %d) as continuation for inline at bci %d",
4279                     cont->block_id(), cont->bci(), bci());
4280     }
4281     continuation_existed = false;
4282   }
4283   // Record number of predecessors of continuation block before
4284   // inlining, to detect if inlined method has edges to its
4285   // continuation after inlining.
4286   int continuation_preds = cont->number_of_preds();
4287 
4288   // Push callee scope
4289   push_scope(callee, cont);
4290 
4291   // the BlockListBuilder for the callee could have bailed out
4292   if (bailed_out())
4293       return false;
4294 
4295   // Temporarily set up bytecode stream so we can append instructions
4296   // (only using the bci of this stream)
4297   scope_data()->set_stream(scope_data()->parent()->stream());
4298 
4299   // Pass parameters into callee state: add assignments
4300   // note: this will also ensure that all arguments are computed before being passed
4301   ValueStack* callee_state = state();
4302   ValueStack* caller_state = state()->caller_state();
4303   for (int i = args_base; i < caller_state->stack_size(); ) {
4304     const int arg_no = i - args_base;
4305     Value arg = caller_state->stack_at_inc(i);
4306     store_local(callee_state, arg, arg_no);
4307   }
4308 
4309   // Remove args from stack.
4310   // Note that we preserve locals state in case we can use it later
4311   // (see use of pop_scope() below)
4312   caller_state->truncate_stack(args_base);
4313   assert(callee_state->stack_size() == 0, "callee stack must be empty");
4314 
4315   Value lock = nullptr;
4316   BlockBegin* sync_handler = nullptr;
4317 
4318   // Inline the locking of the receiver if the callee is synchronized
4319   if (callee->is_synchronized()) {
4320     lock = callee->is_static() ? append(new Constant(new InstanceConstant(callee->holder()->java_mirror())))
4321                                : state()->local_at(0);
4322     sync_handler = new BlockBegin(SynchronizationEntryBCI);
4323     inline_sync_entry(lock, sync_handler);
4324   }
4325 
4326   if (compilation()->env()->dtrace_method_probes()) {
4327     Values* args = new Values(1);
4328     args->push(append(new Constant(new MethodConstant(method()))));
4329     append(new RuntimeCall(voidType, "dtrace_method_entry", CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry), args));
4330   }
4331 
4332   if (profile_inlined_calls()) {
4333     profile_invocation(callee, copy_state_before_with_bci(SynchronizationEntryBCI));
4334   }
4335 
4336   BlockBegin* callee_start_block = block_at(0);
4337   if (callee_start_block != nullptr) {
4338     assert(callee_start_block->is_set(BlockBegin::parser_loop_header_flag), "must be loop header");
4339     Goto* goto_callee = new Goto(callee_start_block, false);
4340     // The state for this goto is in the scope of the callee, so use
4341     // the entry bci for the callee instead of the call site bci.
4342     append_with_bci(goto_callee, 0);
4343     _block->set_end(goto_callee);
4344     callee_start_block->merge(callee_state, compilation()->has_irreducible_loops());
4345 
4346     _last = _block = callee_start_block;
4347 
4348     scope_data()->add_to_work_list(callee_start_block);
4349   }
4350 
4351   // Clear out bytecode stream
4352   scope_data()->set_stream(nullptr);
4353   scope_data()->set_ignore_return(ignore_return);
4354 
4355   CompileLog* log = compilation()->log();
4356   if (log != nullptr) log->head("parse method='%d'", log->identify(callee));
4357 
4358   // Ready to resume parsing in callee (either in the same block we
4359   // were in before or in the callee's start block)
4360   iterate_all_blocks(callee_start_block == nullptr);
4361 
4362   if (log != nullptr) log->done("parse");
4363 
4364   // If we bailed out during parsing, return immediately (this is bad news)
4365   if (bailed_out())
4366       return false;
4367 
4368   // iterate_all_blocks theoretically traverses in random order; in
4369   // practice, we have only traversed the continuation if we are
4370   // inlining into a subroutine
4371   assert(continuation_existed ||
4372          !continuation()->is_set(BlockBegin::was_visited_flag),
4373          "continuation should not have been parsed yet if we created it");
4374 
4375   // At this point we are almost ready to return and resume parsing of
4376   // the caller back in the GraphBuilder. The only thing we want to do
4377   // first is an optimization: during parsing of the callee we
4378   // generated at least one Goto to the continuation block. If we
4379   // generated exactly one, and if the inlined method spanned exactly
4380   // one block (and we didn't have to Goto its entry), then we snip
4381   // off the Goto to the continuation, allowing control to fall
4382   // through back into the caller block and effectively performing
4383   // block merging. This allows load elimination and CSE to take place
4384   // across multiple callee scopes if they are relatively simple, and
4385   // is currently essential to making inlining profitable.
4386   if (num_returns() == 1
4387       && block() == orig_block
4388       && block() == inline_cleanup_block()) {
4389     _last  = inline_cleanup_return_prev();
4390     _state = inline_cleanup_state();
4391   } else if (continuation_preds == cont->number_of_preds()) {
4392     // Inlining caused that the instructions after the invoke in the
4393     // caller are not reachable any more. So skip filling this block
4394     // with instructions!
4395     assert(cont == continuation(), "");
4396     assert(_last && _last->as_BlockEnd(), "");
4397     _skip_block = true;
4398   } else {
4399     // Resume parsing in continuation block unless it was already parsed.
4400     // Note that if we don't change _last here, iteration in
4401     // iterate_bytecodes_for_block will stop when we return.
4402     if (!continuation()->is_set(BlockBegin::was_visited_flag)) {
4403       // add continuation to work list instead of parsing it immediately
4404       assert(_last && _last->as_BlockEnd(), "");
4405       scope_data()->parent()->add_to_work_list(continuation());
4406       _skip_block = true;
4407     }
4408   }
4409 
4410   // Fill the exception handler for synchronized methods with instructions
4411   if (callee->is_synchronized() && sync_handler->state() != nullptr) {
4412     fill_sync_handler(lock, sync_handler);
4413   } else {
4414     pop_scope();
4415   }
4416 
4417   compilation()->notice_inlined_method(callee);
4418 
4419   return true;
4420 }
4421 
4422 
4423 bool GraphBuilder::try_method_handle_inline(ciMethod* callee, bool ignore_return) {
4424   ValueStack* state_before = copy_state_before();
4425   vmIntrinsics::ID iid = callee->intrinsic_id();
4426   switch (iid) {
4427   case vmIntrinsics::_invokeBasic:
4428     {
4429       // get MethodHandle receiver
4430       const int args_base = state()->stack_size() - callee->arg_size();
4431       ValueType* type = state()->stack_at(args_base)->type();
4432       if (type->is_constant()) {
4433         ciObject* mh = type->as_ObjectType()->constant_value();
4434         if (mh->is_method_handle()) {
4435           ciMethod* target = mh->as_method_handle()->get_vmtarget();
4436 
4437           // We don't do CHA here so only inline static and statically bindable methods.
4438           if (target->is_static() || target->can_be_statically_bound()) {
4439             if (ciMethod::is_consistent_info(callee, target)) {
4440               Bytecodes::Code bc = target->is_static() ? Bytecodes::_invokestatic : Bytecodes::_invokevirtual;
4441               ignore_return = ignore_return || (callee->return_type()->is_void() && !target->return_type()->is_void());
4442               if (try_inline(target, /*holder_known*/ !callee->is_static(), ignore_return, bc)) {
4443                 return true;
4444               }
4445             } else {
4446               print_inlining(target, "signatures mismatch", /*success*/ false);
4447             }
4448           } else {
4449             assert(false, "no inlining through MH::invokeBasic"); // missing optimization opportunity due to suboptimal LF shape
4450             print_inlining(target, "not static or statically bindable", /*success*/ false);
4451           }
4452         } else {
4453           assert(mh->is_null_object(), "not a null");
4454           print_inlining(callee, "receiver is always null", /*success*/ false);
4455         }
4456       } else {
4457         print_inlining(callee, "receiver not constant", /*success*/ false);
4458       }
4459     }
4460     break;
4461 
4462   case vmIntrinsics::_linkToVirtual:
4463   case vmIntrinsics::_linkToStatic:
4464   case vmIntrinsics::_linkToSpecial:
4465   case vmIntrinsics::_linkToInterface:
4466     {
4467       // pop MemberName argument
4468       const int args_base = state()->stack_size() - callee->arg_size();
4469       ValueType* type = apop()->type();
4470       if (type->is_constant()) {
4471         ciMethod* target = type->as_ObjectType()->constant_value()->as_member_name()->get_vmtarget();
4472         ignore_return = ignore_return || (callee->return_type()->is_void() && !target->return_type()->is_void());
4473         // If the target is another method handle invoke, try to recursively get
4474         // a better target.
4475         if (target->is_method_handle_intrinsic()) {
4476           if (try_method_handle_inline(target, ignore_return)) {
4477             return true;
4478           }
4479         } else if (!ciMethod::is_consistent_info(callee, target)) {
4480           print_inlining(target, "signatures mismatch", /*success*/ false);
4481         } else {
4482           ciSignature* signature = target->signature();
4483           const int receiver_skip = target->is_static() ? 0 : 1;
4484           // Cast receiver to its type.
4485           if (!target->is_static()) {
4486             ciKlass* tk = signature->accessing_klass();
4487             Value obj = state()->stack_at(args_base);
4488             if (obj->exact_type() == nullptr &&
4489                 obj->declared_type() != tk && tk != compilation()->env()->Object_klass()) {
4490               TypeCast* c = new TypeCast(tk, obj, state_before);
4491               append(c);
4492               state()->stack_at_put(args_base, c);
4493             }
4494           }
4495           // Cast reference arguments to its type.
4496           for (int i = 0, j = 0; i < signature->count(); i++) {
4497             ciType* t = signature->type_at(i);
4498             if (t->is_klass()) {
4499               ciKlass* tk = t->as_klass();
4500               Value obj = state()->stack_at(args_base + receiver_skip + j);
4501               if (obj->exact_type() == nullptr &&
4502                   obj->declared_type() != tk && tk != compilation()->env()->Object_klass()) {
4503                 TypeCast* c = new TypeCast(t, obj, state_before);
4504                 append(c);
4505                 state()->stack_at_put(args_base + receiver_skip + j, c);
4506               }
4507             }
4508             j += t->size();  // long and double take two slots
4509           }
4510           // We don't do CHA here so only inline static and statically bindable methods.
4511           if (target->is_static() || target->can_be_statically_bound()) {
4512             Bytecodes::Code bc = target->is_static() ? Bytecodes::_invokestatic : Bytecodes::_invokevirtual;
4513             if (try_inline(target, /*holder_known*/ !callee->is_static(), ignore_return, bc)) {
4514               return true;
4515             }
4516           } else {
4517             print_inlining(target, "not static or statically bindable", /*success*/ false);
4518           }
4519         }
4520       } else {
4521         print_inlining(callee, "MemberName not constant", /*success*/ false);
4522       }
4523     }
4524     break;
4525 
4526   case vmIntrinsics::_linkToNative:
4527     print_inlining(callee, "native call", /*success*/ false);
4528     break;
4529 
4530   default:
4531     fatal("unexpected intrinsic %d: %s", vmIntrinsics::as_int(iid), vmIntrinsics::name_at(iid));
4532     break;
4533   }
4534   set_state(state_before->copy_for_parsing());
4535   return false;
4536 }
4537 
4538 
4539 void GraphBuilder::inline_bailout(const char* msg) {
4540   assert(msg != nullptr, "inline bailout msg must exist");
4541   _inline_bailout_msg = msg;
4542 }
4543 
4544 
4545 void GraphBuilder::clear_inline_bailout() {
4546   _inline_bailout_msg = nullptr;
4547 }
4548 
4549 
4550 void GraphBuilder::push_root_scope(IRScope* scope, BlockList* bci2block, BlockBegin* start) {
4551   ScopeData* data = new ScopeData(nullptr);
4552   data->set_scope(scope);
4553   data->set_bci2block(bci2block);
4554   _scope_data = data;
4555   _block = start;
4556 }
4557 
4558 
4559 void GraphBuilder::push_scope(ciMethod* callee, BlockBegin* continuation) {
4560   IRScope* callee_scope = new IRScope(compilation(), scope(), bci(), callee, -1, false);
4561   scope()->add_callee(callee_scope);
4562 
4563   BlockListBuilder blb(compilation(), callee_scope, -1);
4564   CHECK_BAILOUT();
4565 
4566   if (!blb.bci2block()->at(0)->is_set(BlockBegin::parser_loop_header_flag)) {
4567     // this scope can be inlined directly into the caller so remove
4568     // the block at bci 0.
4569     blb.bci2block()->at_put(0, nullptr);
4570   }
4571 
4572   set_state(new ValueStack(callee_scope, state()->copy(ValueStack::CallerState, bci())));
4573 
4574   ScopeData* data = new ScopeData(scope_data());
4575   data->set_scope(callee_scope);
4576   data->set_bci2block(blb.bci2block());
4577   data->set_continuation(continuation);
4578   _scope_data = data;
4579 }
4580 
4581 
4582 void GraphBuilder::push_scope_for_jsr(BlockBegin* jsr_continuation, int jsr_dest_bci) {
4583   ScopeData* data = new ScopeData(scope_data());
4584   data->set_parsing_jsr();
4585   data->set_jsr_entry_bci(jsr_dest_bci);
4586   data->set_jsr_return_address_local(-1);
4587   // Must clone bci2block list as we will be mutating it in order to
4588   // properly clone all blocks in jsr region as well as exception
4589   // handlers containing rets
4590   BlockList* new_bci2block = new BlockList(bci2block()->length());
4591   new_bci2block->appendAll(bci2block());
4592   data->set_bci2block(new_bci2block);
4593   data->set_scope(scope());
4594   data->setup_jsr_xhandlers();
4595   data->set_continuation(continuation());
4596   data->set_jsr_continuation(jsr_continuation);
4597   _scope_data = data;
4598 }
4599 
4600 
4601 void GraphBuilder::pop_scope() {
4602   int number_of_locks = scope()->number_of_locks();
4603   _scope_data = scope_data()->parent();
4604   // accumulate minimum number of monitor slots to be reserved
4605   scope()->set_min_number_of_locks(number_of_locks);
4606 }
4607 
4608 
4609 void GraphBuilder::pop_scope_for_jsr() {
4610   _scope_data = scope_data()->parent();
4611 }
4612 
4613 void GraphBuilder::append_unsafe_get(ciMethod* callee, BasicType t, bool is_volatile) {
4614   Values* args = state()->pop_arguments(callee->arg_size());
4615   null_check(args->at(0));
4616   Instruction* offset = args->at(2);
4617 #ifndef _LP64
4618   offset = append(new Convert(Bytecodes::_l2i, offset, as_ValueType(T_INT)));
4619 #endif
4620   Instruction* op = append(new UnsafeGet(t, args->at(1), offset, is_volatile));
4621   push(op->type(), op);
4622   compilation()->set_has_unsafe_access(true);
4623 }
4624 
4625 
4626 void GraphBuilder::append_unsafe_put(ciMethod* callee, BasicType t, bool is_volatile) {
4627   Values* args = state()->pop_arguments(callee->arg_size());
4628   null_check(args->at(0));
4629   Instruction* offset = args->at(2);
4630 #ifndef _LP64
4631   offset = append(new Convert(Bytecodes::_l2i, offset, as_ValueType(T_INT)));
4632 #endif
4633   Value val = args->at(3);
4634   if (t == T_BOOLEAN) {
4635     Value mask = append(new Constant(new IntConstant(1)));
4636     val = append(new LogicOp(Bytecodes::_iand, val, mask));
4637   }
4638   Instruction* op = append(new UnsafePut(t, args->at(1), offset, val, is_volatile));
4639   compilation()->set_has_unsafe_access(true);
4640   kill_all();
4641 }
4642 
4643 void GraphBuilder::append_unsafe_CAS(ciMethod* callee) {
4644   ValueStack* state_before = copy_state_for_exception();
4645   ValueType* result_type = as_ValueType(callee->return_type());
4646   assert(result_type->is_int(), "int result");
4647   Values* args = state()->pop_arguments(callee->arg_size());
4648 
4649   // Pop off some args to specially handle, then push back
4650   Value newval = args->pop();
4651   Value cmpval = args->pop();
4652   Value offset = args->pop();
4653   Value src = args->pop();
4654   Value unsafe_obj = args->pop();
4655 
4656   // Separately handle the unsafe arg. It is not needed for code
4657   // generation, but must be null checked
4658   null_check(unsafe_obj);
4659 
4660 #ifndef _LP64
4661   offset = append(new Convert(Bytecodes::_l2i, offset, as_ValueType(T_INT)));
4662 #endif
4663 
4664   args->push(src);
4665   args->push(offset);
4666   args->push(cmpval);
4667   args->push(newval);
4668 
4669   // An unsafe CAS can alias with other field accesses, but we don't
4670   // know which ones so mark the state as no preserved.  This will
4671   // cause CSE to invalidate memory across it.
4672   bool preserves_state = false;
4673   Intrinsic* result = new Intrinsic(result_type, callee->intrinsic_id(), args, false, state_before, preserves_state);
4674   append_split(result);
4675   push(result_type, result);
4676   compilation()->set_has_unsafe_access(true);
4677 }
4678 
4679 void GraphBuilder::append_char_access(ciMethod* callee, bool is_store) {
4680   // This intrinsic accesses byte[] array as char[] array. Computing the offsets
4681   // correctly requires matched array shapes.
4682   assert (arrayOopDesc::base_offset_in_bytes(T_CHAR) == arrayOopDesc::base_offset_in_bytes(T_BYTE),
4683           "sanity: byte[] and char[] bases agree");
4684   assert (type2aelembytes(T_CHAR) == type2aelembytes(T_BYTE)*2,
4685           "sanity: byte[] and char[] scales agree");
4686 
4687   ValueStack* state_before = copy_state_indexed_access();
4688   compilation()->set_has_access_indexed(true);
4689   Values* args = state()->pop_arguments(callee->arg_size());
4690   Value array = args->at(0);
4691   Value index = args->at(1);
4692   if (is_store) {
4693     Value value = args->at(2);
4694     Instruction* store = append(new StoreIndexed(array, index, nullptr, T_CHAR, value, state_before, false, true));
4695     store->set_flag(Instruction::NeedsRangeCheckFlag, false);
4696     _memory->store_value(value);
4697   } else {
4698     Instruction* load = append(new LoadIndexed(array, index, nullptr, T_CHAR, state_before, true));
4699     load->set_flag(Instruction::NeedsRangeCheckFlag, false);
4700     push(load->type(), load);
4701   }
4702 }
4703 
4704 void GraphBuilder::print_inlining(ciMethod* callee, const char* msg, bool success) {
4705   CompileLog* log = compilation()->log();
4706   if (log != nullptr) {
4707     assert(msg != nullptr, "inlining msg should not be null!");
4708     if (success) {
4709       log->inline_success(msg);
4710     } else {
4711       log->inline_fail(msg);
4712     }
4713   }
4714   EventCompilerInlining event;
4715   if (event.should_commit()) {
4716     CompilerEvent::InlineEvent::post(event, compilation()->env()->task()->compile_id(), method()->get_Method(), callee, success, msg, bci());
4717   }
4718 
4719   CompileTask::print_inlining_ul(callee, scope()->level(), bci(), inlining_result_of(success), msg);
4720 
4721   if (!compilation()->directive()->PrintInliningOption) {
4722     return;
4723   }
4724   CompileTask::print_inlining_tty(callee, scope()->level(), bci(), inlining_result_of(success), msg);
4725   if (success && CIPrintMethodCodes) {
4726     callee->print_codes();
4727   }
4728 }
4729 
4730 void GraphBuilder::append_unsafe_get_and_set(ciMethod* callee, bool is_add) {
4731   Values* args = state()->pop_arguments(callee->arg_size());
4732   BasicType t = callee->return_type()->basic_type();
4733   null_check(args->at(0));
4734   Instruction* offset = args->at(2);
4735 #ifndef _LP64
4736   offset = append(new Convert(Bytecodes::_l2i, offset, as_ValueType(T_INT)));
4737 #endif
4738   Instruction* op = append(new UnsafeGetAndSet(t, args->at(1), offset, args->at(3), is_add));
4739   compilation()->set_has_unsafe_access(true);
4740   kill_all();
4741   push(op->type(), op);
4742 }
4743 
4744 #ifndef PRODUCT
4745 void GraphBuilder::print_stats() {
4746   if (UseLocalValueNumbering) {
4747     vmap()->print();
4748   }
4749 }
4750 #endif // PRODUCT
4751 
4752 void GraphBuilder::profile_call(ciMethod* callee, Value recv, ciKlass* known_holder, Values* obj_args, bool inlined) {
4753   assert(known_holder == nullptr || (known_holder->is_instance_klass() &&
4754                                   (!known_holder->is_interface() ||
4755                                    ((ciInstanceKlass*)known_holder)->has_nonstatic_concrete_methods())), "should be non-static concrete method");
4756   if (known_holder != nullptr) {
4757     if (known_holder->exact_klass() == nullptr) {
4758       known_holder = compilation()->cha_exact_type(known_holder);
4759     }
4760   }
4761 
4762   append(new ProfileCall(method(), bci(), callee, recv, known_holder, obj_args, inlined));
4763 }
4764 
4765 void GraphBuilder::profile_return_type(Value ret, ciMethod* callee, ciMethod* m, int invoke_bci) {
4766   assert((m == nullptr) == (invoke_bci < 0), "invalid method and invalid bci together");
4767   if (m == nullptr) {
4768     m = method();
4769   }
4770   if (invoke_bci < 0) {
4771     invoke_bci = bci();
4772   }
4773   ciMethodData* md = m->method_data_or_null();
4774   ciProfileData* data = md->bci_to_data(invoke_bci);
4775   if (data != nullptr && (data->is_CallTypeData() || data->is_VirtualCallTypeData())) {
4776     bool has_return = data->is_CallTypeData() ? ((ciCallTypeData*)data)->has_return() : ((ciVirtualCallTypeData*)data)->has_return();
4777     if (has_return) {
4778       append(new ProfileReturnType(m , invoke_bci, callee, ret));
4779     }
4780   }
4781 }
4782 
4783 void GraphBuilder::profile_invocation(ciMethod* callee, ValueStack* state) {
4784   append(new ProfileInvoke(callee, state));
4785 }