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