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