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