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