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