1 /*
   2  * Copyright (c) 1997, 2026, 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 "classfile/vmSymbols.hpp"
  26 #include "interpreter/bytecodeStream.hpp"
  27 #include "logging/log.hpp"
  28 #include "logging/logStream.hpp"
  29 #include "memory/allocation.inline.hpp"
  30 #include "memory/resourceArea.hpp"
  31 #include "oops/constantPool.hpp"
  32 #include "oops/generateOopMap.hpp"
  33 #include "oops/oop.inline.hpp"
  34 #include "oops/symbol.hpp"
  35 #include "runtime/handles.inline.hpp"
  36 #include "runtime/java.hpp"
  37 #include "runtime/os.hpp"
  38 #include "runtime/relocator.hpp"
  39 #include "runtime/timerTrace.hpp"
  40 #include "utilities/bitMap.inline.hpp"
  41 #include "utilities/ostream.hpp"
  42 
  43 //
  44 //
  45 // Compute stack layouts for each instruction in method.
  46 //
  47 //  Problems:
  48 //  - What to do about jsr with different types of local vars?
  49 //  Need maps that are conditional on jsr path?
  50 //  - Jsr and exceptions should be done more efficiently (the retAddr stuff)
  51 //
  52 //  Alternative:
  53 //  - Could extend verifier to provide this information.
  54 //    For: one fewer abstract interpreter to maintain. Against: the verifier
  55 //    solves a bigger problem so slower (undesirable to force verification of
  56 //    everything?).
  57 //
  58 //  Algorithm:
  59 //    Partition bytecodes into basic blocks
  60 //    For each basic block: store entry state (vars, stack). For instructions
  61 //    inside basic blocks we do not store any state (instead we recompute it
  62 //    from state produced by previous instruction).
  63 //
  64 //    Perform abstract interpretation of bytecodes over this lattice:
  65 //
  66 //                _--'#'--_
  67 //               /  /  \   \
  68 //             /   /     \   \
  69 //            /    |     |     \
  70 //          'r'   'v'   'p'   ' '
  71 //           \     |     |     /
  72 //            \    \     /    /
  73 //              \   \   /    /
  74 //                -- '@' --
  75 //
  76 //    '#'  top, result of conflict merge
  77 //    'r'  reference type
  78 //    'v'  value type
  79 //    'p'  pc type for jsr/ret
  80 //    ' '  uninitialized; never occurs on operand stack in Java
  81 //    '@'  bottom/unexecuted; initial state each bytecode.
  82 //
  83 //    Basic block headers are the only merge points. We use this iteration to
  84 //    compute the information:
  85 //
  86 //    find basic blocks;
  87 //    initialize them with uninitialized state;
  88 //    initialize first BB according to method signature;
  89 //    mark first BB changed
  90 //    while (some BB is changed) do {
  91 //      perform abstract interpration of all bytecodes in BB;
  92 //      merge exit state of BB into entry state of all successor BBs,
  93 //      noting if any of these change;
  94 //    }
  95 //
  96 //  One additional complication is necessary. The jsr instruction pushes
  97 //  a return PC on the stack (a 'p' type in the abstract interpretation).
  98 //  To be able to process "ret" bytecodes, we keep track of these return
  99 //  PC's in a 'retAddrs' structure in abstract interpreter context (when
 100 //  processing a "ret" bytecodes, it is not sufficient to know that it gets
 101 //  an argument of the right type 'p'; we need to know which address it
 102 //  returns to).
 103 //
 104 // (Note this comment is borrowed form the original author of the algorithm)
 105 
 106 // ComputeCallStack
 107 //
 108 // Specialization of SignatureIterator - compute the effects of a call
 109 //
 110 class ComputeCallStack : public SignatureIterator {
 111   CellTypeState *_effect;
 112   int _idx;
 113 
 114   void setup();
 115   void set(CellTypeState state)         { _effect[_idx++] = state; }
 116   int  length()                         { return _idx; };
 117 
 118   friend class SignatureIterator;  // so do_parameters_on can call do_type
 119   void do_type(BasicType type, bool for_return = false) {
 120     if (for_return && type == T_VOID) {
 121       set(CellTypeState::bottom);
 122     } else if (is_reference_type(type)) {
 123       set(CellTypeState::ref);
 124     } else {
 125       assert(is_java_primitive(type), "");
 126       set(CellTypeState::value);
 127       if (is_double_word_type(type)) {
 128         set(CellTypeState::value);
 129       }
 130     }
 131   }
 132 
 133  public:
 134   ComputeCallStack(Symbol* signature) : SignatureIterator(signature) {};
 135 
 136   // Compute methods
 137   int compute_for_parameters(bool is_static, CellTypeState *effect) {
 138     _idx    = 0;
 139     _effect = effect;
 140 
 141     if (!is_static) {
 142       effect[_idx++] = CellTypeState::ref;
 143     }
 144 
 145     do_parameters_on(this);
 146 
 147     return length();
 148   };
 149 
 150   int compute_for_returntype(CellTypeState *effect) {
 151     _idx    = 0;
 152     _effect = effect;
 153     do_type(return_type(), true);
 154     set(CellTypeState::bottom);  // Always terminate with a bottom state, so ppush works
 155 
 156     return length();
 157   }
 158 };
 159 
 160 //=========================================================================================
 161 // ComputeEntryStack
 162 //
 163 // Specialization of SignatureIterator - in order to set up first stack frame
 164 //
 165 class ComputeEntryStack : public SignatureIterator {
 166   CellTypeState *_effect;
 167   int _idx;
 168 
 169   void setup();
 170   void set(CellTypeState state)         { _effect[_idx++] = state; }
 171   int  length()                         { return _idx; };
 172 
 173   friend class SignatureIterator;  // so do_parameters_on can call do_type
 174   void do_type(BasicType type, bool for_return = false) {
 175     if (for_return && type == T_VOID) {
 176       set(CellTypeState::bottom);
 177     } else if (is_reference_type(type)) {
 178       set(CellTypeState::make_slot_ref(_idx));
 179     } else {
 180       assert(is_java_primitive(type), "");
 181       set(CellTypeState::value);
 182       if (is_double_word_type(type)) {
 183         set(CellTypeState::value);
 184       }
 185     }
 186   }
 187 
 188  public:
 189   ComputeEntryStack(Symbol* signature) : SignatureIterator(signature) {};
 190 
 191   // Compute methods
 192   int compute_for_parameters(bool is_static, CellTypeState *effect) {
 193     _idx    = 0;
 194     _effect = effect;
 195 
 196     if (!is_static)
 197       effect[_idx++] = CellTypeState::make_slot_ref(0);
 198 
 199     do_parameters_on(this);
 200 
 201     return length();
 202   };
 203 
 204   int compute_for_returntype(CellTypeState *effect) {
 205     _idx    = 0;
 206     _effect = effect;
 207     do_type(return_type(), true);
 208     set(CellTypeState::bottom);  // Always terminate with a bottom state, so ppush works
 209 
 210     return length();
 211   }
 212 };
 213 
 214 //=====================================================================================
 215 //
 216 // Implementation of RetTable/RetTableEntry
 217 //
 218 // Contains function to itereate through all bytecodes
 219 // and find all return entry points
 220 //
 221 int RetTable::_init_nof_entries = 10;
 222 int RetTableEntry::_init_nof_jsrs = 5;
 223 
 224 RetTableEntry::RetTableEntry(int target, RetTableEntry *next) {
 225   _target_bci = target;
 226   _jsrs = new GrowableArray<int>(_init_nof_jsrs);
 227   _next = next;
 228 }
 229 
 230 void RetTableEntry::add_delta(int bci, int delta) {
 231   if (_target_bci > bci) _target_bci += delta;
 232 
 233   for (int k = 0; k < _jsrs->length(); k++) {
 234     int jsr = _jsrs->at(k);
 235     if (jsr > bci) _jsrs->at_put(k, jsr+delta);
 236   }
 237 }
 238 
 239 void RetTable::compute_ret_table(const methodHandle& method) {
 240   BytecodeStream i(method);
 241   Bytecodes::Code bytecode;
 242 
 243   while( (bytecode = i.next()) >= 0) {
 244     switch (bytecode) {
 245       case Bytecodes::_jsr:
 246         add_jsr(i.next_bci(), i.dest());
 247         break;
 248       case Bytecodes::_jsr_w:
 249         add_jsr(i.next_bci(), i.dest_w());
 250         break;
 251       default:
 252         break;
 253     }
 254   }
 255 }
 256 
 257 void RetTable::add_jsr(int return_bci, int target_bci) {
 258   RetTableEntry* entry = _first;
 259 
 260   // Scan table for entry
 261   for (;entry && entry->target_bci() != target_bci; entry = entry->next());
 262 
 263   if (!entry) {
 264     // Allocate new entry and put in list
 265     entry = new RetTableEntry(target_bci, _first);
 266     _first = entry;
 267   }
 268 
 269   // Now "entry" is set.  Make sure that the entry is initialized
 270   // and has room for the new jsr.
 271   entry->add_jsr(return_bci);
 272 }
 273 
 274 RetTableEntry* RetTable::find_jsrs_for_target(int targBci) {
 275   RetTableEntry *cur = _first;
 276 
 277   while(cur) {
 278     assert(cur->target_bci() != -1, "sanity check");
 279     if (cur->target_bci() == targBci)  return cur;
 280     cur = cur->next();
 281   }
 282   ShouldNotReachHere();
 283   return nullptr;
 284 }
 285 
 286 // The instruction at bci is changing size by "delta".  Update the return map.
 287 void RetTable::update_ret_table(int bci, int delta) {
 288   RetTableEntry *cur = _first;
 289   while(cur) {
 290     cur->add_delta(bci, delta);
 291     cur = cur->next();
 292   }
 293 }
 294 
 295 //
 296 // Celltype state
 297 //
 298 
 299 CellTypeState CellTypeState::bottom      = CellTypeState::make_bottom();
 300 CellTypeState CellTypeState::uninit      = CellTypeState::make_any(uninit_value);
 301 CellTypeState CellTypeState::ref         = CellTypeState::make_any(ref_conflict);
 302 CellTypeState CellTypeState::value       = CellTypeState::make_any(val_value);
 303 CellTypeState CellTypeState::refUninit   = CellTypeState::make_any(ref_conflict | uninit_value);
 304 CellTypeState CellTypeState::top         = CellTypeState::make_top();
 305 CellTypeState CellTypeState::addr        = CellTypeState::make_any(addr_conflict);
 306 
 307 // Commonly used constants
 308 static CellTypeState epsilonCTS[1] = { CellTypeState::bottom };
 309 static CellTypeState   refCTS   = CellTypeState::ref;
 310 static CellTypeState   valCTS   = CellTypeState::value;
 311 static CellTypeState    vCTS[2] = { CellTypeState::value, CellTypeState::bottom };
 312 static CellTypeState    rCTS[2] = { CellTypeState::ref,   CellTypeState::bottom };
 313 static CellTypeState   rrCTS[3] = { CellTypeState::ref,   CellTypeState::ref,   CellTypeState::bottom };
 314 static CellTypeState   vrCTS[3] = { CellTypeState::value, CellTypeState::ref,   CellTypeState::bottom };
 315 static CellTypeState   vvCTS[3] = { CellTypeState::value, CellTypeState::value, CellTypeState::bottom };
 316 static CellTypeState  rvrCTS[4] = { CellTypeState::ref,   CellTypeState::value, CellTypeState::ref,   CellTypeState::bottom };
 317 static CellTypeState  vvrCTS[4] = { CellTypeState::value, CellTypeState::value, CellTypeState::ref,   CellTypeState::bottom };
 318 static CellTypeState  vvvCTS[4] = { CellTypeState::value, CellTypeState::value, CellTypeState::value, CellTypeState::bottom };
 319 static CellTypeState vvvrCTS[5] = { CellTypeState::value, CellTypeState::value, CellTypeState::value, CellTypeState::ref,   CellTypeState::bottom };
 320 static CellTypeState vvvvCTS[5] = { CellTypeState::value, CellTypeState::value, CellTypeState::value, CellTypeState::value, CellTypeState::bottom };
 321 
 322 char CellTypeState::to_char() const {
 323   if (can_be_reference()) {
 324     if (can_be_value() || can_be_address())
 325       return '#';    // Conflict that needs to be rewritten
 326     else
 327       return 'r';
 328   } else if (can_be_value())
 329     return 'v';
 330   else if (can_be_address())
 331     return 'p';
 332   else if (can_be_uninit())
 333     return ' ';
 334   else
 335     return '@';
 336 }
 337 
 338 
 339 // Print a detailed CellTypeState.  Indicate all bits that are set.  If
 340 // the CellTypeState represents an address or a reference, print the
 341 // value of the additional information.
 342 void CellTypeState::print(outputStream *os) {
 343   if (can_be_address()) {
 344     os->print("(p");
 345   } else {
 346     os->print("( ");
 347   }
 348   if (can_be_reference()) {
 349     os->print("r");
 350   } else {
 351     os->print(" ");
 352   }
 353   if (can_be_value()) {
 354     os->print("v");
 355   } else {
 356     os->print(" ");
 357   }
 358   if (can_be_uninit()) {
 359     os->print("u|");
 360   } else {
 361     os->print(" |");
 362   }
 363   if (is_info_top()) {
 364     os->print("Top)");
 365   } else if (is_info_bottom()) {
 366     os->print("Bot)");
 367   } else {
 368     if (is_reference()) {
 369       int info = get_info();
 370       int data = info & ~(ref_not_lock_bit | ref_slot_bit);
 371       if (info & ref_not_lock_bit) {
 372         // Not a monitor lock reference.
 373         if (info & ref_slot_bit) {
 374           // slot
 375           os->print("slot%d)", data);
 376         } else {
 377           // line
 378           os->print("line%d)", data);
 379         }
 380       } else {
 381         // lock
 382         os->print("lock%d)", data);
 383       }
 384     } else {
 385       os->print("%d)", get_info());
 386     }
 387   }
 388 }
 389 
 390 //
 391 // Basicblock handling methods
 392 //
 393 
 394 void GenerateOopMap::initialize_bb() {
 395   _bb_count  = 0;
 396   _bb_hdr_bits.reinitialize(method()->code_size());
 397 }
 398 
 399 void GenerateOopMap::bb_mark_fct(GenerateOopMap *c, int bci, int *data) {
 400   assert(bci>= 0 && bci < c->method()->code_size(), "index out of bounds");
 401   if (c->is_bb_header(bci))
 402      return;
 403 
 404   if (TraceNewOopMapGeneration) {
 405      tty->print_cr("Basicblock#%d begins at: %d", c->_bb_count, bci);
 406   }
 407   c->set_bbmark_bit(bci);
 408   c->_bb_count++;
 409 }
 410 
 411 
 412 void GenerateOopMap::mark_bbheaders() {
 413   initialize_bb();
 414 
 415   bool fellThrough = false;  // False to get first BB marked.
 416 
 417   // First mark all exception handlers as start of a basic-block
 418   ExceptionTable excps(method());
 419   for(int i = 0; i < excps.length(); i ++) {
 420     bb_mark_fct(this, excps.handler_pc(i), nullptr);
 421   }
 422 
 423   // Then iterate through the code
 424   BytecodeStream bcs(_method);
 425   Bytecodes::Code bytecode;
 426 
 427   while( (bytecode = bcs.next()) >= 0) {
 428     int bci = bcs.bci();
 429 
 430     if (!fellThrough)
 431         bb_mark_fct(this, bci, nullptr);
 432 
 433     fellThrough = jump_targets_do(&bcs, &GenerateOopMap::bb_mark_fct, nullptr);
 434 
 435      /* We will also mark successors of jsr's as basic block headers. */
 436     switch (bytecode) {
 437       case Bytecodes::_jsr:
 438       case Bytecodes::_jsr_w:
 439         assert(!fellThrough, "should not happen");
 440         // If this is the last bytecode, there is no successor to mark
 441         if (bci + Bytecodes::length_for(bytecode) < method()->code_size()) {
 442           bb_mark_fct(this, bci + Bytecodes::length_for(bytecode), nullptr);
 443         }
 444         break;
 445       default:
 446         break;
 447     }
 448   }
 449 }
 450 
 451 void GenerateOopMap::set_bbmark_bit(int bci) {
 452   _bb_hdr_bits.at_put(bci, true);
 453 }
 454 
 455 void GenerateOopMap::reachable_basicblock(GenerateOopMap *c, int bci, int *data) {
 456   assert(bci>= 0 && bci < c->method()->code_size(), "index out of bounds");
 457   BasicBlock* bb = c->get_basic_block_at(bci);
 458   if (bb->is_dead()) {
 459     bb->mark_as_alive();
 460     *data = 1; // Mark basicblock as changed
 461   }
 462 }
 463 
 464 
 465 void GenerateOopMap::mark_reachable_code() {
 466   int change = 1; // int to get function pointers to work
 467 
 468   // Mark entry basic block as alive and all exception handlers
 469   _basic_blocks[0].mark_as_alive();
 470   ExceptionTable excps(method());
 471   for(int i = 0; i < excps.length(); i++) {
 472     BasicBlock *bb = get_basic_block_at(excps.handler_pc(i));
 473     // If block is not already alive (due to multiple exception handlers to same bb), then
 474     // make it alive
 475     if (bb->is_dead()) bb->mark_as_alive();
 476   }
 477 
 478   BytecodeStream bcs(_method);
 479 
 480   // Iterate through all basic blocks until we reach a fixpoint
 481   while (change) {
 482     change = 0;
 483 
 484     for (int i = 0; i < _bb_count; i++) {
 485       BasicBlock *bb = &_basic_blocks[i];
 486       if (bb->is_alive()) {
 487         // Position bytecodestream at last bytecode in basicblock
 488         bcs.set_start(bb->_end_bci);
 489         bcs.next();
 490         Bytecodes::Code bytecode = bcs.code();
 491         int bci = bcs.bci();
 492         assert(bci == bb->_end_bci, "wrong bci");
 493 
 494         bool fell_through = jump_targets_do(&bcs, &GenerateOopMap::reachable_basicblock, &change);
 495 
 496         // We will also mark successors of jsr's as alive.
 497         switch (bytecode) {
 498           case Bytecodes::_jsr:
 499           case Bytecodes::_jsr_w:
 500             assert(!fell_through, "should not happen");
 501             // If this is the last bytecode, there is no successor to mark
 502             if (bci + Bytecodes::length_for(bytecode) < method()->code_size()) {
 503               reachable_basicblock(this, bci + Bytecodes::length_for(bytecode), &change);
 504             }
 505             break;
 506           default:
 507             break;
 508         }
 509         if (fell_through) {
 510           // Mark successor as alive
 511           if (bb[1].is_dead()) {
 512             bb[1].mark_as_alive();
 513             change = 1;
 514           }
 515         }
 516       }
 517     }
 518   }
 519 }
 520 
 521 /* If the current instruction in "c" has no effect on control flow,
 522    returns "true".  Otherwise, calls "jmpFct" one or more times, with
 523    "c", an appropriate "pcDelta", and "data" as arguments, then
 524    returns "false".  There is one exception: if the current
 525    instruction is a "ret", returns "false" without calling "jmpFct".
 526    Arrangements for tracking the control flow of a "ret" must be made
 527    externally. */
 528 bool GenerateOopMap::jump_targets_do(BytecodeStream *bcs, jmpFct_t jmpFct, int *data) {
 529   int bci = bcs->bci();
 530 
 531   switch (bcs->code()) {
 532     case Bytecodes::_ifeq:
 533     case Bytecodes::_ifne:
 534     case Bytecodes::_iflt:
 535     case Bytecodes::_ifge:
 536     case Bytecodes::_ifgt:
 537     case Bytecodes::_ifle:
 538     case Bytecodes::_if_icmpeq:
 539     case Bytecodes::_if_icmpne:
 540     case Bytecodes::_if_icmplt:
 541     case Bytecodes::_if_icmpge:
 542     case Bytecodes::_if_icmpgt:
 543     case Bytecodes::_if_icmple:
 544     case Bytecodes::_if_acmpeq:
 545     case Bytecodes::_if_acmpne:
 546     case Bytecodes::_ifnull:
 547     case Bytecodes::_ifnonnull:
 548       (*jmpFct)(this, bcs->dest(), data);
 549       // Class files verified by the old verifier can have a conditional branch
 550       // as their last bytecode, provided the conditional branch is unreachable
 551       // during execution.  Check if this instruction is the method's last bytecode
 552       // and, if so, don't call the jmpFct.
 553       if (bci + 3 < method()->code_size()) {
 554         (*jmpFct)(this, bci + 3, data);
 555       }
 556       break;
 557 
 558     case Bytecodes::_goto:
 559       (*jmpFct)(this, bcs->dest(), data);
 560       break;
 561     case Bytecodes::_goto_w:
 562       (*jmpFct)(this, bcs->dest_w(), data);
 563       break;
 564     case Bytecodes::_tableswitch:
 565       { Bytecode_tableswitch tableswitch(method(), bcs->bcp());
 566         int len = tableswitch.length();
 567 
 568         (*jmpFct)(this, bci + tableswitch.default_offset(), data); /* Default. jump address */
 569         while (--len >= 0) {
 570           (*jmpFct)(this, bci + tableswitch.dest_offset_at(len), data);
 571         }
 572         break;
 573       }
 574 
 575     case Bytecodes::_lookupswitch:
 576       { Bytecode_lookupswitch lookupswitch(method(), bcs->bcp());
 577         int npairs = lookupswitch.number_of_pairs();
 578         (*jmpFct)(this, bci + lookupswitch.default_offset(), data); /* Default. */
 579         while(--npairs >= 0) {
 580           LookupswitchPair pair = lookupswitch.pair_at(npairs);
 581           (*jmpFct)(this, bci + pair.offset(), data);
 582         }
 583         break;
 584       }
 585     case Bytecodes::_jsr:
 586       assert(bcs->is_wide()==false, "sanity check");
 587       (*jmpFct)(this, bcs->dest(), data);
 588       break;
 589     case Bytecodes::_jsr_w:
 590       (*jmpFct)(this, bcs->dest_w(), data);
 591       break;
 592     case Bytecodes::_wide:
 593       ShouldNotReachHere();
 594       return true;
 595       break;
 596     case Bytecodes::_athrow:
 597     case Bytecodes::_ireturn:
 598     case Bytecodes::_lreturn:
 599     case Bytecodes::_freturn:
 600     case Bytecodes::_dreturn:
 601     case Bytecodes::_areturn:
 602     case Bytecodes::_return:
 603     case Bytecodes::_ret:
 604       break;
 605     default:
 606       return true;
 607   }
 608   return false;
 609 }
 610 
 611 /* Requires "pc" to be the head of a basic block; returns that basic
 612    block. */
 613 BasicBlock *GenerateOopMap::get_basic_block_at(int bci) const {
 614   BasicBlock* bb = get_basic_block_containing(bci);
 615   assert(bb->_bci == bci, "should have found BB");
 616   return bb;
 617 }
 618 
 619 // Requires "pc" to be the start of an instruction; returns the basic
 620 //   block containing that instruction. */
 621 BasicBlock  *GenerateOopMap::get_basic_block_containing(int bci) const {
 622   BasicBlock *bbs = _basic_blocks;
 623   int lo = 0, hi = _bb_count - 1;
 624 
 625   while (lo <= hi) {
 626     int m = (lo + hi) / 2;
 627     int mbci = bbs[m]._bci;
 628     int nbci;
 629 
 630     if ( m == _bb_count-1) {
 631       assert( bci >= mbci && bci < method()->code_size(), "sanity check failed");
 632       return bbs+m;
 633     } else {
 634       nbci = bbs[m+1]._bci;
 635     }
 636 
 637     if ( mbci <= bci && bci < nbci) {
 638       return bbs+m;
 639     } else if (mbci < bci) {
 640       lo = m + 1;
 641     } else {
 642       assert(mbci > bci, "sanity check");
 643       hi = m - 1;
 644     }
 645   }
 646 
 647   fatal("should have found BB");
 648   return nullptr;
 649 }
 650 
 651 void GenerateOopMap::restore_state(BasicBlock *bb)
 652 {
 653   memcpy(_state, bb->_state, _state_len*sizeof(CellTypeState));
 654   _stack_top = bb->_stack_top;
 655   _monitor_top = bb->_monitor_top;
 656 }
 657 
 658 int GenerateOopMap::next_bb_start_pc(BasicBlock *bb) {
 659  intptr_t bbNum = bb - _basic_blocks + 1;
 660  if (bbNum == _bb_count)
 661     return method()->code_size();
 662 
 663  return _basic_blocks[bbNum]._bci;
 664 }
 665 
 666 //
 667 // CellType handling methods
 668 //
 669 
 670 // Allocate memory and throw LinkageError if failure.
 671 #define ALLOC_RESOURCE_ARRAY(var, type, count)                           \
 672   var = NEW_RESOURCE_ARRAY_RETURN_NULL(type, count);                     \
 673   if (var == nullptr) {                                                  \
 674     report_error("Cannot reserve enough memory to analyze this method"); \
 675     return;                                                              \
 676   }
 677 
 678 
 679 void GenerateOopMap::init_state() {
 680   _state_len     = _max_locals + _max_stack + _max_monitors;
 681   ALLOC_RESOURCE_ARRAY(_state, CellTypeState, _state_len);
 682   memset(_state, 0, _state_len * sizeof(CellTypeState));
 683   int count = MAX3(_max_locals, _max_stack, _max_monitors) + 1/*for null terminator char */;
 684   ALLOC_RESOURCE_ARRAY(_state_vec_buf, char, count);
 685 }
 686 
 687 void GenerateOopMap::make_context_uninitialized() {
 688   CellTypeState* vs = vars();
 689 
 690   for (int i = 0; i < _max_locals; i++)
 691       vs[i] = CellTypeState::uninit;
 692 
 693   _stack_top = 0;
 694   _monitor_top = 0;
 695 }
 696 
 697 int GenerateOopMap::methodsig_to_effect(Symbol* signature, bool is_static, CellTypeState* effect) {
 698   ComputeEntryStack ces(signature);
 699   return ces.compute_for_parameters(is_static, effect);
 700 }
 701 
 702 // Return result of merging cts1 and cts2.
 703 CellTypeState CellTypeState::merge(CellTypeState cts, int slot) const {
 704   CellTypeState result;
 705 
 706   assert(!is_bottom() && !cts.is_bottom(),
 707          "merge of bottom values is handled elsewhere");
 708 
 709   result._state = _state | cts._state;
 710 
 711   // If the top bit is set, we don't need to do any more work.
 712   if (!result.is_info_top()) {
 713     assert((result.can_be_address() || result.can_be_reference()),
 714            "only addresses and references have non-top info");
 715 
 716     if (!equal(cts)) {
 717       // The two values being merged are different.  Raise to top.
 718       if (result.is_reference()) {
 719         result = CellTypeState::make_slot_ref(slot);
 720       } else {
 721         result._state |= info_conflict;
 722       }
 723     }
 724   }
 725   assert(result.is_valid_state(), "checking that CTS merge maintains legal state");
 726 
 727   return result;
 728 }
 729 
 730 // Merge the variable state for locals and stack from cts into bbts.
 731 bool GenerateOopMap::merge_local_state_vectors(CellTypeState* cts,
 732                                                CellTypeState* bbts) {
 733   int i;
 734   int len = _max_locals + _stack_top;
 735   bool change = false;
 736 
 737   for (i = len - 1; i >= 0; i--) {
 738     CellTypeState v = cts[i].merge(bbts[i], i);
 739     change = change || !v.equal(bbts[i]);
 740     bbts[i] = v;
 741   }
 742 
 743   return change;
 744 }
 745 
 746 // Merge the monitor stack state from cts into bbts.
 747 bool GenerateOopMap::merge_monitor_state_vectors(CellTypeState* cts,
 748                                                  CellTypeState* bbts) {
 749   bool change = false;
 750   if (_max_monitors > 0 && _monitor_top != bad_monitors) {
 751     // If there are no monitors in the program, or there has been
 752     // a monitor matching error before this point in the program,
 753     // then we do not merge in the monitor state.
 754 
 755     int base = _max_locals + _max_stack;
 756     int len = base + _monitor_top;
 757     for (int i = len - 1; i >= base; i--) {
 758       CellTypeState v = cts[i].merge(bbts[i], i);
 759 
 760       // Can we prove that, when there has been a change, it will already
 761       // have been detected at this point?  That would make this equal
 762       // check here unnecessary.
 763       change = change || !v.equal(bbts[i]);
 764       bbts[i] = v;
 765     }
 766   }
 767 
 768   return change;
 769 }
 770 
 771 void GenerateOopMap::copy_state(CellTypeState *dst, CellTypeState *src) {
 772   int len = _max_locals + _stack_top;
 773   for (int i = 0; i < len; i++) {
 774     if (src[i].is_nonlock_reference()) {
 775       dst[i] = CellTypeState::make_slot_ref(i);
 776     } else {
 777       dst[i] = src[i];
 778     }
 779   }
 780   if (_max_monitors > 0 && _monitor_top != bad_monitors) {
 781     int base = _max_locals + _max_stack;
 782     len = base + _monitor_top;
 783     for (int i = base; i < len; i++) {
 784       dst[i] = src[i];
 785     }
 786   }
 787 }
 788 
 789 
 790 // Merge the states for the current block and the next.  As long as a
 791 // block is reachable the locals and stack must be merged.  If the
 792 // stack heights don't match then this is a verification error and
 793 // it's impossible to interpret the code.  Simultaneously monitor
 794 // states are being check to see if they nest statically.  If monitor
 795 // depths match up then their states are merged.  Otherwise the
 796 // mismatch is simply recorded and interpretation continues since
 797 // monitor matching is purely informational and doesn't say anything
 798 // about the correctness of the code.
 799 void GenerateOopMap::merge_state_into_bb(BasicBlock *bb) {
 800   guarantee(bb != nullptr, "null basicblock");
 801   assert(bb->is_alive(), "merging state into a dead basicblock");
 802 
 803   if (_stack_top == bb->_stack_top) {
 804     // always merge local state even if monitors don't match.
 805     if (merge_local_state_vectors(_state, bb->_state)) {
 806       bb->set_changed(true);
 807     }
 808     if (_monitor_top == bb->_monitor_top) {
 809       // monitors still match so continue merging monitor states.
 810       if (merge_monitor_state_vectors(_state, bb->_state)) {
 811         bb->set_changed(true);
 812       }
 813     } else {
 814       if (log_is_enabled(Info, monitormismatch)) {
 815         report_monitor_mismatch("monitor stack height merge conflict");
 816       }
 817       // When the monitor stacks are not matched, we set _monitor_top to
 818       // bad_monitors.  This signals that, from here on, the monitor stack cannot
 819       // be trusted.  In particular, monitorexit bytecodes may throw
 820       // exceptions.  We mark this block as changed so that the change
 821       // propagates properly.
 822       bb->_monitor_top = bad_monitors;
 823       bb->set_changed(true);
 824       _monitor_safe = false;
 825     }
 826   } else if (!bb->is_reachable()) {
 827     // First time we look at this  BB
 828     copy_state(bb->_state, _state);
 829     bb->_stack_top = _stack_top;
 830     bb->_monitor_top = _monitor_top;
 831     bb->set_changed(true);
 832   } else {
 833     verify_error("stack height conflict: %d vs. %d",  _stack_top, bb->_stack_top);
 834   }
 835 }
 836 
 837 void GenerateOopMap::merge_state(GenerateOopMap *gom, int bci, int* data) {
 838    gom->merge_state_into_bb(gom->get_basic_block_at(bci));
 839 }
 840 
 841 void GenerateOopMap::set_var(int localNo, CellTypeState cts) {
 842   assert(cts.is_reference() || cts.is_value() || cts.is_address(),
 843          "wrong celltypestate");
 844   if (localNo < 0 || localNo > _max_locals) {
 845     verify_error("variable write error: r%d", localNo);
 846     return;
 847   }
 848   vars()[localNo] = cts;
 849 }
 850 
 851 CellTypeState GenerateOopMap::get_var(int localNo) {
 852   assert(localNo < _max_locals + _nof_refval_conflicts, "variable read error");
 853   if (localNo < 0 || localNo > _max_locals) {
 854     verify_error("variable read error: r%d", localNo);
 855     return valCTS; // just to pick something;
 856   }
 857   return vars()[localNo];
 858 }
 859 
 860 CellTypeState GenerateOopMap::pop() {
 861   if ( _stack_top <= 0) {
 862     verify_error("stack underflow");
 863     return valCTS; // just to pick something
 864   }
 865   return  stack()[--_stack_top];
 866 }
 867 
 868 void GenerateOopMap::push(CellTypeState cts) {
 869   if ( _stack_top >= _max_stack) {
 870     verify_error("stack overflow");
 871     return;
 872   }
 873   stack()[_stack_top++] = cts;
 874 }
 875 
 876 CellTypeState GenerateOopMap::monitor_pop() {
 877   assert(_monitor_top != bad_monitors, "monitor_pop called on error monitor stack");
 878   if (_monitor_top == 0) {
 879     // We have detected a pop of an empty monitor stack.
 880     _monitor_safe = false;
 881      _monitor_top = bad_monitors;
 882 
 883     if (log_is_enabled(Info, monitormismatch)) {
 884       report_monitor_mismatch("monitor stack underflow");
 885     }
 886     return CellTypeState::ref; // just to keep the analysis going.
 887   }
 888   return  monitors()[--_monitor_top];
 889 }
 890 
 891 void GenerateOopMap::monitor_push(CellTypeState cts) {
 892   assert(_monitor_top != bad_monitors, "monitor_push called on error monitor stack");
 893   if (_monitor_top >= _max_monitors) {
 894     // Some monitorenter is being executed more than once.
 895     // This means that the monitor stack cannot be simulated.
 896     _monitor_safe = false;
 897     _monitor_top = bad_monitors;
 898 
 899     if (log_is_enabled(Info, monitormismatch)) {
 900       report_monitor_mismatch("monitor stack overflow");
 901     }
 902     return;
 903   }
 904   monitors()[_monitor_top++] = cts;
 905 }
 906 
 907 //
 908 // Interpretation handling methods
 909 //
 910 
 911 void GenerateOopMap::do_interpretation()
 912 {
 913   // "i" is just for debugging, so we can detect cases where this loop is
 914   // iterated more than once.
 915   int i = 0;
 916   do {
 917 #ifndef PRODUCT
 918     if (TraceNewOopMapGeneration) {
 919       tty->print("\n\nIteration #%d of do_interpretation loop, method:\n", i);
 920       method()->print_name(tty);
 921       tty->print("\n\n");
 922     }
 923 #endif
 924     _conflict = false;
 925     _monitor_safe = true;
 926     // init_state is now called from init_basic_blocks.  The length of a
 927     // state vector cannot be determined until we have made a pass through
 928     // the bytecodes counting the possible monitor entries.
 929     if (!_got_error) init_basic_blocks();
 930     if (!_got_error) setup_method_entry_state();
 931     if (!_got_error) interp_all();
 932     if (!_got_error) rewrite_refval_conflicts();
 933     i++;
 934   } while (_conflict && !_got_error);
 935 }
 936 
 937 void GenerateOopMap::init_basic_blocks() {
 938   // Note: Could consider reserving only the needed space for each BB's state
 939   // (entry stack may not be of maximal height for every basic block).
 940   // But cumbersome since we don't know the stack heights yet.  (Nor the
 941   // monitor stack heights...)
 942 
 943   ALLOC_RESOURCE_ARRAY(_basic_blocks, BasicBlock, _bb_count);
 944 
 945   // Make a pass through the bytecodes.  Count the number of monitorenters.
 946   // This can be used an upper bound on the monitor stack depth in programs
 947   // which obey stack discipline with their monitor usage.  Initialize the
 948   // known information about basic blocks.
 949   BytecodeStream j(_method);
 950   Bytecodes::Code bytecode;
 951 
 952   int bbNo = 0;
 953   int monitor_count = 0;
 954   int prev_bci = -1;
 955   while( (bytecode = j.next()) >= 0) {
 956     if (j.code() == Bytecodes::_monitorenter) {
 957       monitor_count++;
 958     }
 959 
 960     int bci = j.bci();
 961     if (is_bb_header(bci)) {
 962       // Initialize the basicblock structure
 963       BasicBlock *bb   = _basic_blocks + bbNo;
 964       bb->_bci         = bci;
 965       bb->_max_locals  = _max_locals;
 966       bb->_max_stack   = _max_stack;
 967       bb->set_changed(false);
 968       bb->_stack_top   = BasicBlock::_dead_basic_block; // Initialize all basicblocks are dead.
 969       bb->_monitor_top = bad_monitors;
 970 
 971       if (bbNo > 0) {
 972         _basic_blocks[bbNo - 1]._end_bci = prev_bci;
 973       }
 974 
 975       bbNo++;
 976     }
 977     // Remember previous bci.
 978     prev_bci = bci;
 979   }
 980   // Set
 981   _basic_blocks[bbNo-1]._end_bci = prev_bci;
 982 
 983 
 984   // Check that the correct number of basicblocks was found
 985   if (bbNo !=_bb_count) {
 986     if (bbNo < _bb_count) {
 987       verify_error("jump into the middle of instruction?");
 988       return;
 989     } else {
 990       verify_error("extra basic blocks - should not happen?");
 991       return;
 992     }
 993   }
 994 
 995   _max_monitors = monitor_count;
 996 
 997   // Now that we have a bound on the depth of the monitor stack, we can
 998   // initialize the CellTypeState-related information.
 999   init_state();
1000 
1001   // We allocate space for all state-vectors for all basicblocks in one huge
1002   // chunk.  Then in the next part of the code, we set a pointer in each
1003   // _basic_block that points to each piece.
1004 
1005   // The product of bbNo and _state_len can get large if there are lots of
1006   // basic blocks and stack/locals/monitors.  Need to check to make sure
1007   // we don't overflow the capacity of a pointer.
1008   if ((unsigned)bbNo > UINTPTR_MAX / sizeof(CellTypeState) / _state_len) {
1009     report_error("The amount of memory required to analyze this method "
1010                  "exceeds addressable range");
1011     return;
1012   }
1013 
1014   CellTypeState *basicBlockState;
1015   ALLOC_RESOURCE_ARRAY(basicBlockState, CellTypeState, bbNo * _state_len);
1016   memset(basicBlockState, 0, bbNo * _state_len * sizeof(CellTypeState));
1017 
1018   // Make a pass over the basicblocks and assign their state vectors.
1019   for (int blockNum=0; blockNum < bbNo; blockNum++) {
1020     BasicBlock *bb = _basic_blocks + blockNum;
1021     bb->_state = basicBlockState + blockNum * _state_len;
1022 
1023 #ifdef ASSERT
1024     if (blockNum + 1 < bbNo) {
1025       address bcp = _method->bcp_from(bb->_end_bci);
1026       int bc_len = Bytecodes::java_length_at(_method(), bcp);
1027       assert(bb->_end_bci + bc_len == bb[1]._bci, "unmatched bci info in basicblock");
1028     }
1029 #endif
1030   }
1031 #ifdef ASSERT
1032   { BasicBlock *bb = &_basic_blocks[bbNo-1];
1033     address bcp = _method->bcp_from(bb->_end_bci);
1034     int bc_len = Bytecodes::java_length_at(_method(), bcp);
1035     assert(bb->_end_bci + bc_len == _method->code_size(), "wrong end bci");
1036   }
1037 #endif
1038 
1039   // Mark all alive blocks
1040   mark_reachable_code();
1041 }
1042 
1043 void GenerateOopMap::setup_method_entry_state() {
1044 
1045     // Initialize all locals to 'uninit' and set stack-height to 0
1046     make_context_uninitialized();
1047 
1048     // Initialize CellState type of arguments
1049     methodsig_to_effect(method()->signature(), method()->is_static(), vars());
1050 
1051     // If some references must be pre-assigned to null, then set that up
1052     initialize_vars();
1053 
1054     // This is the start state
1055     merge_state_into_bb(&_basic_blocks[0]);
1056 
1057     assert(_basic_blocks[0].changed(), "we are not getting off the ground");
1058 }
1059 
1060 // The instruction at bci is changing size by "delta".  Update the basic blocks.
1061 void GenerateOopMap::update_basic_blocks(int bci, int delta,
1062                                          int new_method_size) {
1063   assert(new_method_size >= method()->code_size() + delta,
1064          "new method size is too small");
1065 
1066   _bb_hdr_bits.reinitialize(new_method_size);
1067 
1068   for(int k = 0; k < _bb_count; k++) {
1069     if (_basic_blocks[k]._bci > bci) {
1070       _basic_blocks[k]._bci     += delta;
1071       _basic_blocks[k]._end_bci += delta;
1072     }
1073     _bb_hdr_bits.at_put(_basic_blocks[k]._bci, true);
1074   }
1075 }
1076 
1077 //
1078 // Initvars handling
1079 //
1080 
1081 void GenerateOopMap::initialize_vars() {
1082   for (int k = 0; k < _init_vars->length(); k++)
1083     _state[_init_vars->at(k)] = CellTypeState::make_slot_ref(k);
1084 }
1085 
1086 void GenerateOopMap::add_to_ref_init_set(int localNo) {
1087 
1088   if (TraceNewOopMapGeneration)
1089     tty->print_cr("Added init vars: %d", localNo);
1090 
1091   // Is it already in the set?
1092   if (_init_vars->contains(localNo) )
1093     return;
1094 
1095    _init_vars->append(localNo);
1096 }
1097 
1098 //
1099 // Interpreration code
1100 //
1101 
1102 void GenerateOopMap::interp_all() {
1103   bool change = true;
1104 
1105   while (change && !_got_error) {
1106     change = false;
1107     for (int i = 0; i < _bb_count && !_got_error; i++) {
1108       BasicBlock *bb = &_basic_blocks[i];
1109       if (bb->changed()) {
1110          if (_got_error) return;
1111          change = true;
1112          bb->set_changed(false);
1113          interp_bb(bb);
1114       }
1115     }
1116   }
1117 }
1118 
1119 void GenerateOopMap::interp_bb(BasicBlock *bb) {
1120 
1121   // We do not want to do anything in case the basic-block has not been initialized. This
1122   // will happen in the case where there is dead-code hang around in a method.
1123   assert(bb->is_reachable(), "should be reachable or deadcode exist");
1124   restore_state(bb);
1125 
1126   BytecodeStream itr(_method);
1127 
1128   // Set iterator interval to be the current basicblock
1129   int lim_bci = next_bb_start_pc(bb);
1130   itr.set_interval(bb->_bci, lim_bci);
1131   assert(lim_bci != bb->_bci, "must be at least one instruction in a basicblock");
1132   itr.next(); // read first instruction
1133 
1134   // Iterates through all bytecodes except the last in a basic block.
1135   // We handle the last one special, since there is controlflow change.
1136   while(itr.next_bci() < lim_bci && !_got_error) {
1137     if (_has_exceptions || _monitor_top != 0) {
1138       // We do not need to interpret the results of exceptional
1139       // continuation from this instruction when the method has no
1140       // exception handlers and the monitor stack is currently
1141       // empty.
1142       do_exception_edge(&itr);
1143     }
1144     interp1(&itr);
1145     itr.next();
1146   }
1147 
1148   // Handle last instruction.
1149   if (!_got_error) {
1150     assert(itr.next_bci() == lim_bci, "must point to end");
1151     if (_has_exceptions || _monitor_top != 0) {
1152       do_exception_edge(&itr);
1153     }
1154     interp1(&itr);
1155 
1156     bool fall_through = jump_targets_do(&itr, GenerateOopMap::merge_state, nullptr);
1157     if (_got_error)  return;
1158 
1159     if (itr.code() == Bytecodes::_ret) {
1160       assert(!fall_through, "cannot be set if ret instruction");
1161       // Automatically handles 'wide' ret indices
1162       ret_jump_targets_do(&itr, GenerateOopMap::merge_state, itr.get_index(), nullptr);
1163     } else if (fall_through) {
1164      // Hit end of BB, but the instr. was a fall-through instruction,
1165      // so perform transition as if the BB ended in a "jump".
1166      if (lim_bci != bb[1]._bci) {
1167        verify_error("bytecodes fell through last instruction");
1168        return;
1169      }
1170      merge_state_into_bb(bb + 1);
1171     }
1172   }
1173 }
1174 
1175 void GenerateOopMap::do_exception_edge(BytecodeStream* itr) {
1176   // Only check exception edge, if bytecode can trap
1177   if (!Bytecodes::can_trap(itr->code())) return;
1178   switch (itr->code()) {
1179     case Bytecodes::_aload_0:
1180       // These bytecodes can trap for rewriting.  We need to assume that
1181       // they do not throw exceptions to make the monitor analysis work.
1182       return;
1183 
1184     case Bytecodes::_ireturn:
1185     case Bytecodes::_lreturn:
1186     case Bytecodes::_freturn:
1187     case Bytecodes::_dreturn:
1188     case Bytecodes::_areturn:
1189     case Bytecodes::_return:
1190       // If the monitor stack height is not zero when we leave the method,
1191       // then we are either exiting with a non-empty stack or we have
1192       // found monitor trouble earlier in our analysis.  In either case,
1193       // assume an exception could be taken here.
1194       if (_monitor_top == 0) {
1195         return;
1196       }
1197       break;
1198 
1199     case Bytecodes::_monitorexit:
1200       // If the monitor stack height is bad_monitors, then we have detected a
1201       // monitor matching problem earlier in the analysis.  If the
1202       // monitor stack height is 0, we are about to pop a monitor
1203       // off of an empty stack.  In either case, the bytecode
1204       // could throw an exception.
1205       if (_monitor_top != bad_monitors && _monitor_top != 0) {
1206         return;
1207       }
1208       break;
1209 
1210     default:
1211       break;
1212   }
1213 
1214   if (_has_exceptions) {
1215     int bci = itr->bci();
1216     ExceptionTable exct(method());
1217     for(int i = 0; i< exct.length(); i++) {
1218       int start_pc   = exct.start_pc(i);
1219       int end_pc     = exct.end_pc(i);
1220       int handler_pc = exct.handler_pc(i);
1221       int catch_type = exct.catch_type_index(i);
1222 
1223       if (start_pc <= bci && bci < end_pc) {
1224         BasicBlock *excBB = get_basic_block_at(handler_pc);
1225         guarantee(excBB != nullptr, "no basic block for exception");
1226         CellTypeState *excStk = excBB->stack();
1227         CellTypeState *cOpStck = stack();
1228         CellTypeState cOpStck_0 = cOpStck[0];
1229         int cOpStackTop = _stack_top;
1230 
1231         // Exception stacks are always the same.
1232         assert(method()->max_stack() > 0, "sanity check");
1233 
1234         // We remembered the size and first element of "cOpStck"
1235         // above; now we temporarily set them to the appropriate
1236         // values for an exception handler. */
1237         cOpStck[0] = CellTypeState::make_slot_ref(_max_locals);
1238         _stack_top = 1;
1239 
1240         merge_state_into_bb(excBB);
1241 
1242         // Now undo the temporary change.
1243         cOpStck[0] = cOpStck_0;
1244         _stack_top = cOpStackTop;
1245 
1246         // If this is a "catch all" handler, then we do not need to
1247         // consider any additional handlers.
1248         if (catch_type == 0) {
1249           return;
1250         }
1251       }
1252     }
1253   }
1254 
1255   // It is possible that none of the exception handlers would have caught
1256   // the exception.  In this case, we will exit the method.  We must
1257   // ensure that the monitor stack is empty in this case.
1258   if (_monitor_top == 0) {
1259     return;
1260   }
1261 
1262   // We pessimistically assume that this exception can escape the
1263   // method. (It is possible that it will always be caught, but
1264   // we don't care to analyse the types of the catch clauses.)
1265 
1266   // We don't set _monitor_top to bad_monitors because there are no successors
1267   // to this exceptional exit.
1268 
1269   if (log_is_enabled(Info, monitormismatch) && _monitor_safe) {
1270     // We check _monitor_safe so that we only report the first mismatched
1271     // exceptional exit.
1272     report_monitor_mismatch("non-empty monitor stack at exceptional exit");
1273   }
1274   _monitor_safe = false;
1275 
1276 }
1277 
1278 void GenerateOopMap::report_monitor_mismatch(const char *msg) {
1279   LogStream ls(Log(monitormismatch)::info());
1280   ls.print("Monitor mismatch in method ");
1281   method()->print_short_name(&ls);
1282   ls.print_cr(": %s", msg);
1283 }
1284 
1285 void GenerateOopMap::print_states(outputStream *os,
1286                                   CellTypeState* vec, int num) {
1287   for (int i = 0; i < num; i++) {
1288     vec[i].print(tty);
1289   }
1290 }
1291 
1292 // Print the state values at the current bytecode.
1293 void GenerateOopMap::print_current_state(outputStream   *os,
1294                                          BytecodeStream *currentBC,
1295                                          bool            detailed) {
1296   if (detailed) {
1297     os->print("     %4d vars     = ", currentBC->bci());
1298     print_states(os, vars(), _max_locals);
1299     os->print("    %s", Bytecodes::name(currentBC->code()));
1300   } else {
1301     os->print("    %4d  vars = '%s' ", currentBC->bci(),  state_vec_to_string(vars(), _max_locals));
1302     os->print("     stack = '%s' ", state_vec_to_string(stack(), _stack_top));
1303     if (_monitor_top != bad_monitors) {
1304       os->print("  monitors = '%s'  \t%s", state_vec_to_string(monitors(), _monitor_top), Bytecodes::name(currentBC->code()));
1305     } else {
1306       os->print("  [bad monitor stack]");
1307     }
1308   }
1309 
1310   switch(currentBC->code()) {
1311     case Bytecodes::_invokevirtual:
1312     case Bytecodes::_invokespecial:
1313     case Bytecodes::_invokestatic:
1314     case Bytecodes::_invokedynamic:
1315     case Bytecodes::_invokeinterface: {
1316       int idx = currentBC->has_index_u4() ? currentBC->get_index_u4() : currentBC->get_index_u2();
1317       ConstantPool* cp      = method()->constants();
1318       int nameAndTypeIdx    = cp->name_and_type_ref_index_at(idx, currentBC->code());
1319       int signatureIdx      = cp->signature_ref_index_at(nameAndTypeIdx);
1320       Symbol* signature     = cp->symbol_at(signatureIdx);
1321       os->print("%s", signature->as_C_string());
1322     }
1323     default:
1324       break;
1325   }
1326 
1327   if (detailed) {
1328     os->cr();
1329     os->print("          stack    = ");
1330     print_states(os, stack(), _stack_top);
1331     os->cr();
1332     if (_monitor_top != bad_monitors) {
1333       os->print("          monitors = ");
1334       print_states(os, monitors(), _monitor_top);
1335     } else {
1336       os->print("          [bad monitor stack]");
1337     }
1338   }
1339 
1340   os->cr();
1341 }
1342 
1343 // Sets the current state to be the state after executing the
1344 // current instruction, starting in the current state.
1345 void GenerateOopMap::interp1(BytecodeStream *itr) {
1346   if (TraceNewOopMapGeneration) {
1347     print_current_state(tty, itr, TraceNewOopMapGenerationDetailed);
1348   }
1349 
1350   // Should we report the results? Result is reported *before* the instruction at the current bci is executed.
1351   // However, not for calls. For calls we do not want to include the arguments, so we postpone the reporting until
1352   // they have been popped (in method ppl).
1353   if (_report_result == true) {
1354     switch(itr->code()) {
1355       case Bytecodes::_invokevirtual:
1356       case Bytecodes::_invokespecial:
1357       case Bytecodes::_invokestatic:
1358       case Bytecodes::_invokedynamic:
1359       case Bytecodes::_invokeinterface:
1360         _itr_send = itr;
1361         _report_result_for_send = true;
1362         break;
1363       default:
1364        fill_stackmap_for_opcodes(itr, vars(), stack(), _stack_top);
1365        break;
1366     }
1367   }
1368 
1369   // abstract interpretation of current opcode
1370   switch(itr->code()) {
1371     case Bytecodes::_nop:                                           break;
1372     case Bytecodes::_goto:                                          break;
1373     case Bytecodes::_goto_w:                                        break;
1374     case Bytecodes::_iinc:                                          break;
1375     case Bytecodes::_return:            do_return_monitor_check();
1376                                         break;
1377 
1378     case Bytecodes::_aconst_null:
1379     case Bytecodes::_new:               ppush1(CellTypeState::make_line_ref(itr->bci()));
1380                                         break;
1381 
1382     case Bytecodes::_iconst_m1:
1383     case Bytecodes::_iconst_0:
1384     case Bytecodes::_iconst_1:
1385     case Bytecodes::_iconst_2:
1386     case Bytecodes::_iconst_3:
1387     case Bytecodes::_iconst_4:
1388     case Bytecodes::_iconst_5:
1389     case Bytecodes::_fconst_0:
1390     case Bytecodes::_fconst_1:
1391     case Bytecodes::_fconst_2:
1392     case Bytecodes::_bipush:
1393     case Bytecodes::_sipush:            ppush1(valCTS);             break;
1394 
1395     case Bytecodes::_lconst_0:
1396     case Bytecodes::_lconst_1:
1397     case Bytecodes::_dconst_0:
1398     case Bytecodes::_dconst_1:          ppush(vvCTS);               break;
1399 
1400     case Bytecodes::_ldc2_w:            ppush(vvCTS);               break;
1401 
1402     case Bytecodes::_ldc:               // fall through:
1403     case Bytecodes::_ldc_w:             do_ldc(itr->bci());         break;
1404 
1405     case Bytecodes::_iload:
1406     case Bytecodes::_fload:             ppload(vCTS, itr->get_index()); break;
1407 
1408     case Bytecodes::_lload:
1409     case Bytecodes::_dload:             ppload(vvCTS,itr->get_index()); break;
1410 
1411     case Bytecodes::_aload:             ppload(rCTS, itr->get_index()); break;
1412 
1413     case Bytecodes::_iload_0:
1414     case Bytecodes::_fload_0:           ppload(vCTS, 0);            break;
1415     case Bytecodes::_iload_1:
1416     case Bytecodes::_fload_1:           ppload(vCTS, 1);            break;
1417     case Bytecodes::_iload_2:
1418     case Bytecodes::_fload_2:           ppload(vCTS, 2);            break;
1419     case Bytecodes::_iload_3:
1420     case Bytecodes::_fload_3:           ppload(vCTS, 3);            break;
1421 
1422     case Bytecodes::_lload_0:
1423     case Bytecodes::_dload_0:           ppload(vvCTS, 0);           break;
1424     case Bytecodes::_lload_1:
1425     case Bytecodes::_dload_1:           ppload(vvCTS, 1);           break;
1426     case Bytecodes::_lload_2:
1427     case Bytecodes::_dload_2:           ppload(vvCTS, 2);           break;
1428     case Bytecodes::_lload_3:
1429     case Bytecodes::_dload_3:           ppload(vvCTS, 3);           break;
1430 
1431     case Bytecodes::_aload_0:           ppload(rCTS, 0);            break;
1432     case Bytecodes::_aload_1:           ppload(rCTS, 1);            break;
1433     case Bytecodes::_aload_2:           ppload(rCTS, 2);            break;
1434     case Bytecodes::_aload_3:           ppload(rCTS, 3);            break;
1435 
1436     case Bytecodes::_iaload:
1437     case Bytecodes::_faload:
1438     case Bytecodes::_baload:
1439     case Bytecodes::_caload:
1440     case Bytecodes::_saload:            pp(vrCTS, vCTS); break;
1441 
1442     case Bytecodes::_laload:            pp(vrCTS, vvCTS);  break;
1443     case Bytecodes::_daload:            pp(vrCTS, vvCTS); break;
1444 
1445     case Bytecodes::_aaload:            pp_new_ref(vrCTS, itr->bci()); break;
1446 
1447     case Bytecodes::_istore:
1448     case Bytecodes::_fstore:            ppstore(vCTS, itr->get_index()); break;
1449 
1450     case Bytecodes::_lstore:
1451     case Bytecodes::_dstore:            ppstore(vvCTS, itr->get_index()); break;
1452 
1453     case Bytecodes::_astore:            do_astore(itr->get_index());     break;
1454 
1455     case Bytecodes::_istore_0:
1456     case Bytecodes::_fstore_0:          ppstore(vCTS, 0);           break;
1457     case Bytecodes::_istore_1:
1458     case Bytecodes::_fstore_1:          ppstore(vCTS, 1);           break;
1459     case Bytecodes::_istore_2:
1460     case Bytecodes::_fstore_2:          ppstore(vCTS, 2);           break;
1461     case Bytecodes::_istore_3:
1462     case Bytecodes::_fstore_3:          ppstore(vCTS, 3);           break;
1463 
1464     case Bytecodes::_lstore_0:
1465     case Bytecodes::_dstore_0:          ppstore(vvCTS, 0);          break;
1466     case Bytecodes::_lstore_1:
1467     case Bytecodes::_dstore_1:          ppstore(vvCTS, 1);          break;
1468     case Bytecodes::_lstore_2:
1469     case Bytecodes::_dstore_2:          ppstore(vvCTS, 2);          break;
1470     case Bytecodes::_lstore_3:
1471     case Bytecodes::_dstore_3:          ppstore(vvCTS, 3);          break;
1472 
1473     case Bytecodes::_astore_0:          do_astore(0);               break;
1474     case Bytecodes::_astore_1:          do_astore(1);               break;
1475     case Bytecodes::_astore_2:          do_astore(2);               break;
1476     case Bytecodes::_astore_3:          do_astore(3);               break;
1477 
1478     case Bytecodes::_iastore:
1479     case Bytecodes::_fastore:
1480     case Bytecodes::_bastore:
1481     case Bytecodes::_castore:
1482     case Bytecodes::_sastore:           ppop(vvrCTS);               break;
1483     case Bytecodes::_lastore:
1484     case Bytecodes::_dastore:           ppop(vvvrCTS);              break;
1485     case Bytecodes::_aastore:           ppop(rvrCTS);               break;
1486 
1487     case Bytecodes::_pop:               ppop_any(1);                break;
1488     case Bytecodes::_pop2:              ppop_any(2);                break;
1489 
1490     case Bytecodes::_dup:               ppdupswap(1, "11");         break;
1491     case Bytecodes::_dup_x1:            ppdupswap(2, "121");        break;
1492     case Bytecodes::_dup_x2:            ppdupswap(3, "1321");       break;
1493     case Bytecodes::_dup2:              ppdupswap(2, "2121");       break;
1494     case Bytecodes::_dup2_x1:           ppdupswap(3, "21321");      break;
1495     case Bytecodes::_dup2_x2:           ppdupswap(4, "214321");     break;
1496     case Bytecodes::_swap:              ppdupswap(2, "12");         break;
1497 
1498     case Bytecodes::_iadd:
1499     case Bytecodes::_fadd:
1500     case Bytecodes::_isub:
1501     case Bytecodes::_fsub:
1502     case Bytecodes::_imul:
1503     case Bytecodes::_fmul:
1504     case Bytecodes::_idiv:
1505     case Bytecodes::_fdiv:
1506     case Bytecodes::_irem:
1507     case Bytecodes::_frem:
1508     case Bytecodes::_ishl:
1509     case Bytecodes::_ishr:
1510     case Bytecodes::_iushr:
1511     case Bytecodes::_iand:
1512     case Bytecodes::_ior:
1513     case Bytecodes::_ixor:
1514     case Bytecodes::_l2f:
1515     case Bytecodes::_l2i:
1516     case Bytecodes::_d2f:
1517     case Bytecodes::_d2i:
1518     case Bytecodes::_fcmpl:
1519     case Bytecodes::_fcmpg:             pp(vvCTS, vCTS); break;
1520 
1521     case Bytecodes::_ladd:
1522     case Bytecodes::_dadd:
1523     case Bytecodes::_lsub:
1524     case Bytecodes::_dsub:
1525     case Bytecodes::_lmul:
1526     case Bytecodes::_dmul:
1527     case Bytecodes::_ldiv:
1528     case Bytecodes::_ddiv:
1529     case Bytecodes::_lrem:
1530     case Bytecodes::_drem:
1531     case Bytecodes::_land:
1532     case Bytecodes::_lor:
1533     case Bytecodes::_lxor:              pp(vvvvCTS, vvCTS); break;
1534 
1535     case Bytecodes::_ineg:
1536     case Bytecodes::_fneg:
1537     case Bytecodes::_i2f:
1538     case Bytecodes::_f2i:
1539     case Bytecodes::_i2c:
1540     case Bytecodes::_i2s:
1541     case Bytecodes::_i2b:               pp(vCTS, vCTS); break;
1542 
1543     case Bytecodes::_lneg:
1544     case Bytecodes::_dneg:
1545     case Bytecodes::_l2d:
1546     case Bytecodes::_d2l:               pp(vvCTS, vvCTS); break;
1547 
1548     case Bytecodes::_lshl:
1549     case Bytecodes::_lshr:
1550     case Bytecodes::_lushr:             pp(vvvCTS, vvCTS); break;
1551 
1552     case Bytecodes::_i2l:
1553     case Bytecodes::_i2d:
1554     case Bytecodes::_f2l:
1555     case Bytecodes::_f2d:               pp(vCTS, vvCTS); break;
1556 
1557     case Bytecodes::_lcmp:              pp(vvvvCTS, vCTS); break;
1558     case Bytecodes::_dcmpl:
1559     case Bytecodes::_dcmpg:             pp(vvvvCTS, vCTS); break;
1560 
1561     case Bytecodes::_ifeq:
1562     case Bytecodes::_ifne:
1563     case Bytecodes::_iflt:
1564     case Bytecodes::_ifge:
1565     case Bytecodes::_ifgt:
1566     case Bytecodes::_ifle:
1567     case Bytecodes::_tableswitch:       ppop1(valCTS);
1568                                         break;
1569     case Bytecodes::_ireturn:
1570     case Bytecodes::_freturn:           do_return_monitor_check();
1571                                         ppop1(valCTS);
1572                                         break;
1573     case Bytecodes::_if_icmpeq:
1574     case Bytecodes::_if_icmpne:
1575     case Bytecodes::_if_icmplt:
1576     case Bytecodes::_if_icmpge:
1577     case Bytecodes::_if_icmpgt:
1578     case Bytecodes::_if_icmple:         ppop(vvCTS);
1579                                         break;
1580 
1581     case Bytecodes::_lreturn:           do_return_monitor_check();
1582                                         ppop(vvCTS);
1583                                         break;
1584 
1585     case Bytecodes::_dreturn:           do_return_monitor_check();
1586                                         ppop(vvCTS);
1587                                         break;
1588 
1589     case Bytecodes::_if_acmpeq:
1590     case Bytecodes::_if_acmpne:         ppop(rrCTS);                 break;
1591 
1592     case Bytecodes::_jsr:               do_jsr(itr->dest());         break;
1593     case Bytecodes::_jsr_w:             do_jsr(itr->dest_w());       break;
1594 
1595     case Bytecodes::_getstatic:         do_field(true,   true,  itr->get_index_u2(), itr->bci(), itr->code()); break;
1596     case Bytecodes::_putstatic:         do_field(false,  true,  itr->get_index_u2(), itr->bci(), itr->code()); break;
1597     case Bytecodes::_getfield:          do_field(true,   false, itr->get_index_u2(), itr->bci(), itr->code()); break;
1598     case Bytecodes::_putfield:          do_field(false,  false, itr->get_index_u2(), itr->bci(), itr->code()); break;
1599 
1600     case Bytecodes::_invokeinterface:
1601     case Bytecodes::_invokevirtual:
1602     case Bytecodes::_invokespecial:     do_method(false, itr->get_index_u2(), itr->bci(), itr->code()); break;
1603     case Bytecodes::_invokestatic:      do_method(true , itr->get_index_u2(), itr->bci(), itr->code()); break;
1604     case Bytecodes::_invokedynamic:     do_method(true , itr->get_index_u4(), itr->bci(), itr->code()); break;
1605     case Bytecodes::_newarray:
1606     case Bytecodes::_anewarray:         pp_new_ref(vCTS, itr->bci()); break;
1607     case Bytecodes::_checkcast:         do_checkcast(); break;
1608     case Bytecodes::_arraylength:
1609     case Bytecodes::_instanceof:        pp(rCTS, vCTS); break;
1610     case Bytecodes::_monitorenter:      do_monitorenter(itr->bci()); break;
1611     case Bytecodes::_monitorexit:       do_monitorexit(itr->bci()); break;
1612 
1613     case Bytecodes::_athrow:            // handled by do_exception_edge() BUT ...
1614                                         // vlh(apple): do_exception_edge() does not get
1615                                         // called if method has no exception handlers
1616                                         if ((!_has_exceptions) && (_monitor_top > 0)) {
1617                                           _monitor_safe = false;
1618                                         }
1619                                         break;
1620 
1621     case Bytecodes::_areturn:           do_return_monitor_check();
1622                                         ppop1(refCTS);
1623                                         break;
1624 
1625     case Bytecodes::_ifnull:
1626     case Bytecodes::_ifnonnull:         ppop1(refCTS); break;
1627     case Bytecodes::_multianewarray:    do_multianewarray(*(itr->bcp()+3), itr->bci()); break;
1628 
1629     case Bytecodes::_wide:              fatal("Iterator should skip this bytecode"); break;
1630     case Bytecodes::_ret:                                           break;
1631 
1632     // Java opcodes
1633     case Bytecodes::_lookupswitch:      ppop1(valCTS);             break;
1634 
1635     default:
1636          tty->print("unexpected opcode: %d\n", itr->code());
1637          ShouldNotReachHere();
1638     break;
1639   }
1640 }
1641 
1642 void GenerateOopMap::check_type(CellTypeState expected, CellTypeState actual) {
1643   if (!expected.equal_kind(actual)) {
1644     verify_error("wrong type on stack (found: %c expected: %c)", actual.to_char(), expected.to_char());
1645   }
1646 }
1647 
1648 void GenerateOopMap::ppstore(CellTypeState *in, int loc_no) {
1649   while(!(*in).is_bottom()) {
1650     CellTypeState expected =*in++;
1651     CellTypeState actual   = pop();
1652     check_type(expected, actual);
1653     assert(loc_no >= 0, "sanity check");
1654     set_var(loc_no++, actual);
1655   }
1656 }
1657 
1658 void GenerateOopMap::ppload(CellTypeState *out, int loc_no) {
1659   while(!(*out).is_bottom()) {
1660     CellTypeState out1 = *out++;
1661     CellTypeState vcts = get_var(loc_no);
1662     assert(out1.can_be_reference() || out1.can_be_value(),
1663            "can only load refs. and values.");
1664     if (out1.is_reference()) {
1665       assert(loc_no>=0, "sanity check");
1666       if (!vcts.is_reference()) {
1667         // We were asked to push a reference, but the type of the
1668         // variable can be something else
1669         _conflict = true;
1670         if (vcts.can_be_uninit()) {
1671           // It is a ref-uninit conflict (at least). If there are other
1672           // problems, we'll get them in the next round
1673           add_to_ref_init_set(loc_no);
1674           vcts = out1;
1675         } else {
1676           // It wasn't a ref-uninit conflict. So must be a
1677           // ref-val or ref-pc conflict. Split the variable.
1678           record_refval_conflict(loc_no);
1679           vcts = out1;
1680         }
1681         push(out1); // recover...
1682       } else {
1683         push(vcts); // preserve reference.
1684       }
1685       // Otherwise it is a conflict, but one that verification would
1686       // have caught if illegal. In particular, it can't be a topCTS
1687       // resulting from mergeing two difference pcCTS's since the verifier
1688       // would have rejected any use of such a merge.
1689     } else {
1690       push(out1); // handle val/init conflict
1691     }
1692     loc_no++;
1693   }
1694 }
1695 
1696 void GenerateOopMap::ppdupswap(int poplen, const char *out) {
1697   CellTypeState actual[5];
1698   assert(poplen < 5, "this must be less than length of actual vector");
1699 
1700   // Pop all arguments.
1701   for (int i = 0; i < poplen; i++) {
1702     actual[i] = pop();
1703   }
1704   // Field _state is uninitialized when calling push.
1705   for (int i = poplen; i < 5; i++) {
1706     actual[i] = CellTypeState::uninit;
1707   }
1708 
1709   // put them back
1710   char push_ch = *out++;
1711   while (push_ch != '\0') {
1712     int idx = push_ch - '1';
1713     assert(idx >= 0 && idx < poplen, "wrong arguments");
1714     push(actual[idx]);
1715     push_ch = *out++;
1716   }
1717 }
1718 
1719 void GenerateOopMap::ppop1(CellTypeState out) {
1720   CellTypeState actual = pop();
1721   check_type(out, actual);
1722 }
1723 
1724 void GenerateOopMap::ppop(CellTypeState *out) {
1725   while (!(*out).is_bottom()) {
1726     ppop1(*out++);
1727   }
1728 }
1729 
1730 void GenerateOopMap::ppush1(CellTypeState in) {
1731   assert(in.is_reference() || in.is_value(), "sanity check");
1732   push(in);
1733 }
1734 
1735 void GenerateOopMap::ppush(CellTypeState *in) {
1736   while (!(*in).is_bottom()) {
1737     ppush1(*in++);
1738   }
1739 }
1740 
1741 void GenerateOopMap::pp(CellTypeState *in, CellTypeState *out) {
1742   ppop(in);
1743   ppush(out);
1744 }
1745 
1746 void GenerateOopMap::pp_new_ref(CellTypeState *in, int bci) {
1747   ppop(in);
1748   ppush1(CellTypeState::make_line_ref(bci));
1749 }
1750 
1751 void GenerateOopMap::ppop_any(int poplen) {
1752   if (_stack_top >= poplen) {
1753     _stack_top -= poplen;
1754   } else {
1755     verify_error("stack underflow");
1756   }
1757 }
1758 
1759 // Replace all occurrences of the state 'match' with the state 'replace'
1760 // in our current state vector.
1761 void GenerateOopMap::replace_all_CTS_matches(CellTypeState match,
1762                                              CellTypeState replace) {
1763   int i;
1764   int len = _max_locals + _stack_top;
1765   bool change = false;
1766 
1767   for (i = len - 1; i >= 0; i--) {
1768     if (match.equal(_state[i])) {
1769       _state[i] = replace;
1770     }
1771   }
1772 
1773   if (_monitor_top > 0) {
1774     int base = _max_locals + _max_stack;
1775     len = base + _monitor_top;
1776     for (i = len - 1; i >= base; i--) {
1777       if (match.equal(_state[i])) {
1778         _state[i] = replace;
1779       }
1780     }
1781   }
1782 }
1783 
1784 void GenerateOopMap::do_checkcast() {
1785   CellTypeState actual = pop();
1786   check_type(refCTS, actual);
1787   push(actual);
1788 }
1789 
1790 void GenerateOopMap::do_monitorenter(int bci) {
1791   CellTypeState actual = pop();
1792   if (_monitor_top == bad_monitors) {
1793     return;
1794   }
1795 
1796   // Bail out when we get repeated locks on an identical monitor.  This case
1797   // isn't too hard to handle and can be made to work if supporting nested
1798   // redundant synchronized statements becomes a priority.
1799   //
1800   // See also "Note" in do_monitorexit(), below.
1801   if (actual.is_lock_reference()) {
1802     _monitor_top = bad_monitors;
1803     _monitor_safe = false;
1804 
1805     if (log_is_enabled(Info, monitormismatch)) {
1806       report_monitor_mismatch("nested redundant lock -- bailout...");
1807     }
1808     return;
1809   }
1810 
1811   CellTypeState lock = CellTypeState::make_lock_ref(bci);
1812   check_type(refCTS, actual);
1813   if (!actual.is_info_top()) {
1814     replace_all_CTS_matches(actual, lock);
1815     monitor_push(lock);
1816   }
1817 }
1818 
1819 void GenerateOopMap::do_monitorexit(int bci) {
1820   CellTypeState actual = pop();
1821   if (_monitor_top == bad_monitors) {
1822     return;
1823   }
1824   check_type(refCTS, actual);
1825   CellTypeState expected = monitor_pop();
1826   if (!actual.is_lock_reference() || !expected.equal(actual)) {
1827     // The monitor we are exiting is not verifiably the one
1828     // on the top of our monitor stack.  This causes a monitor
1829     // mismatch.
1830     _monitor_top = bad_monitors;
1831     _monitor_safe = false;
1832 
1833     // We need to mark this basic block as changed so that
1834     // this monitorexit will be visited again.  We need to
1835     // do this to ensure that we have accounted for the
1836     // possibility that this bytecode will throw an
1837     // exception.
1838     BasicBlock* bb = get_basic_block_containing(bci);
1839     guarantee(bb != nullptr, "no basic block for bci");
1840     bb->set_changed(true);
1841     bb->_monitor_top = bad_monitors;
1842 
1843     if (log_is_enabled(Info, monitormismatch)) {
1844       report_monitor_mismatch("improper monitor pair");
1845     }
1846   } else {
1847     // This code is a fix for the case where we have repeated
1848     // locking of the same object in straightline code.  We clear
1849     // out the lock when it is popped from the monitor stack
1850     // and replace it with an unobtrusive reference value that can
1851     // be locked again.
1852     //
1853     // Note: when generateOopMap is fixed to properly handle repeated,
1854     //       nested, redundant locks on the same object, then this
1855     //       fix will need to be removed at that time.
1856     replace_all_CTS_matches(actual, CellTypeState::make_line_ref(bci));
1857   }
1858 }
1859 
1860 void GenerateOopMap::do_return_monitor_check() {
1861   if (_monitor_top > 0) {
1862     // The monitor stack must be empty when we leave the method
1863     // for the monitors to be properly matched.
1864     _monitor_safe = false;
1865 
1866     // Since there are no successors to the *return bytecode, it
1867     // isn't necessary to set _monitor_top to bad_monitors.
1868 
1869     if (log_is_enabled(Info, monitormismatch)) {
1870       report_monitor_mismatch("non-empty monitor stack at return");
1871     }
1872   }
1873 }
1874 
1875 void GenerateOopMap::do_jsr(int targ_bci) {
1876   push(CellTypeState::make_addr(targ_bci));
1877 }
1878 
1879 
1880 
1881 void GenerateOopMap::do_ldc(int bci) {
1882   Bytecode_loadconstant ldc(methodHandle(Thread::current(), method()), bci);
1883   ConstantPool* cp  = method()->constants();
1884   constantTag tag = cp->tag_at(ldc.pool_index()); // idx is index in resolved_references
1885   BasicType       bt  = ldc.result_type();
1886 #ifdef ASSERT
1887   BasicType   tag_bt = (tag.is_dynamic_constant() || tag.is_dynamic_constant_in_error()) ? bt : tag.basic_type();
1888   assert(bt == tag_bt, "same result");
1889 #endif
1890   CellTypeState   cts;
1891   if (is_reference_type(bt)) {  // could be T_ARRAY with condy
1892     assert(!tag.is_string_index() && !tag.is_klass_index(), "Unexpected index tag");
1893     cts = CellTypeState::make_line_ref(bci);
1894   } else {
1895     cts = valCTS;
1896   }
1897   ppush1(cts);
1898 }
1899 
1900 void GenerateOopMap::do_multianewarray(int dims, int bci) {
1901   assert(dims >= 1, "sanity check");
1902   for(int i = dims -1; i >=0; i--) {
1903     ppop1(valCTS);
1904   }
1905   ppush1(CellTypeState::make_line_ref(bci));
1906 }
1907 
1908 void GenerateOopMap::do_astore(int idx) {
1909   CellTypeState r_or_p = pop();
1910   if (!r_or_p.is_address() && !r_or_p.is_reference()) {
1911     // We actually expected ref or pc, but we only report that we expected a ref. It does not
1912     // really matter (at least for now)
1913     verify_error("wrong type on stack (found: %c, expected: {pr})", r_or_p.to_char());
1914     return;
1915   }
1916   set_var(idx, r_or_p);
1917 }
1918 
1919 // Copies bottom/zero terminated CTS string from "src" into "dst".
1920 //   Does NOT terminate with a bottom. Returns the number of cells copied.
1921 int GenerateOopMap::copy_cts(CellTypeState *dst, CellTypeState *src) {
1922   int idx = 0;
1923   while (!src[idx].is_bottom()) {
1924     dst[idx] = src[idx];
1925     idx++;
1926   }
1927   return idx;
1928 }
1929 
1930 void GenerateOopMap::do_field(int is_get, int is_static, int idx, int bci, Bytecodes::Code bc) {
1931   // Dig up signature for field in constant pool
1932   ConstantPool* cp     = method()->constants();
1933   int nameAndTypeIdx     = cp->name_and_type_ref_index_at(idx, bc);
1934   int signatureIdx       = cp->signature_ref_index_at(nameAndTypeIdx);
1935   Symbol* signature      = cp->symbol_at(signatureIdx);
1936 
1937   CellTypeState temp[4];
1938   CellTypeState *eff  = signature_to_effect(signature, bci, temp);
1939 
1940   CellTypeState in[4];
1941   CellTypeState *out;
1942   int i =  0;
1943 
1944   if (is_get) {
1945     out = eff;
1946   } else {
1947     out = epsilonCTS;
1948     i   = copy_cts(in, eff);
1949   }
1950   if (!is_static) {
1951     in[i++] = CellTypeState::ref;
1952   }
1953   in[i] = CellTypeState::bottom;
1954   assert(i<=3, "sanity check");
1955   pp(in, out);
1956 }
1957 
1958 void GenerateOopMap::do_method(int is_static, int idx, int bci, Bytecodes::Code bc) {
1959  // Dig up signature for field in constant pool
1960   ConstantPool* cp  = _method->constants();
1961   Symbol* signature   = cp->signature_ref_at(idx, bc);
1962 
1963   // Parse method signature
1964   CellTypeState out[4];
1965   CellTypeState in[MAXARGSIZE+1];   // Includes result
1966   ComputeCallStack cse(signature);
1967 
1968   // Compute return type
1969   int res_length=  cse.compute_for_returntype(out);
1970 
1971   // Temporary hack.
1972   if (out[0].equal(CellTypeState::ref) && out[1].equal(CellTypeState::bottom)) {
1973     out[0] = CellTypeState::make_line_ref(bci);
1974   }
1975 
1976   assert(res_length<=4, "max value should be vv");
1977 
1978   // Compute arguments
1979   int arg_length = cse.compute_for_parameters(is_static != 0, in);
1980   assert(arg_length<=MAXARGSIZE, "too many locals");
1981 
1982   // Pop arguments
1983   for (int i = arg_length - 1; i >= 0; i--) ppop1(in[i]);// Do args in reverse order.
1984 
1985   // Report results
1986   if (_report_result_for_send == true) {
1987      fill_stackmap_for_opcodes(_itr_send, vars(), stack(), _stack_top);
1988      _report_result_for_send = false;
1989   }
1990 
1991   // Push return address
1992   ppush(out);
1993 }
1994 
1995 // This is used to parse the signature for fields, since they are very simple...
1996 CellTypeState *GenerateOopMap::signature_to_effect(const Symbol* sig, int bci, CellTypeState *out) {
1997   // Object and array
1998   BasicType bt = Signature::basic_type(sig);
1999   if (is_reference_type(bt)) {
2000     out[0] = CellTypeState::make_line_ref(bci);
2001     out[1] = CellTypeState::bottom;
2002     return out;
2003   }
2004   if (is_double_word_type(bt)) return vvCTS; // Long and Double
2005   if (bt == T_VOID) return epsilonCTS;       // Void
2006   return vCTS;                               // Otherwise
2007 }
2008 
2009 uint64_t GenerateOopMap::_total_byte_count = 0;
2010 elapsedTimer GenerateOopMap::_total_oopmap_time;
2011 
2012 // This function assumes "bcs" is at a "ret" instruction and that the vars
2013 // state is valid for that instruction. Furthermore, the ret instruction
2014 // must be the last instruction in "bb" (we store information about the
2015 // "ret" in "bb").
2016 void GenerateOopMap::ret_jump_targets_do(BytecodeStream *bcs, jmpFct_t jmpFct, int varNo, int *data) {
2017   CellTypeState ra = vars()[varNo];
2018   if (!ra.is_good_address()) {
2019     verify_error("ret returns from two jsr subroutines?");
2020     return;
2021   }
2022   int target = ra.get_info();
2023 
2024   RetTableEntry* rtEnt = _rt.find_jsrs_for_target(target);
2025   int bci = bcs->bci();
2026   for (int i = 0; i < rtEnt->nof_jsrs(); i++) {
2027     int target_bci = rtEnt->jsrs(i);
2028     // Make sure a jrtRet does not set the changed bit for dead basicblock.
2029     BasicBlock* jsr_bb    = get_basic_block_containing(target_bci - 1);
2030     DEBUG_ONLY(BasicBlock* target_bb = &jsr_bb[1];)
2031     assert(target_bb  == get_basic_block_at(target_bci), "wrong calc. of successor basicblock");
2032     bool alive = jsr_bb->is_alive();
2033     if (TraceNewOopMapGeneration) {
2034       tty->print("pc = %d, ret -> %d alive: %s\n", bci, target_bci, alive ? "true" : "false");
2035     }
2036     if (alive) jmpFct(this, target_bci, data);
2037   }
2038 }
2039 
2040 //
2041 // Debug method
2042 //
2043 char* GenerateOopMap::state_vec_to_string(CellTypeState* vec, int len) {
2044 #ifdef ASSERT
2045   int checklen = MAX3(_max_locals, _max_stack, _max_monitors) + 1;
2046   assert(len < checklen, "state_vec_buf overflow");
2047 #endif
2048   for (int i = 0; i < len; i++) _state_vec_buf[i] = vec[i].to_char();
2049   _state_vec_buf[len] = 0;
2050   return _state_vec_buf;
2051 }
2052 
2053 void GenerateOopMap::print_time() {
2054   tty->print_cr ("Accumulated oopmap times:");
2055   tty->print_cr ("---------------------------");
2056   tty->print_cr ("  Total : %3.3f sec.", GenerateOopMap::_total_oopmap_time.seconds());
2057   tty->print_cr ("  (%3.0f bytecodes per sec) ",
2058   (double)GenerateOopMap::_total_byte_count / GenerateOopMap::_total_oopmap_time.seconds());
2059 }
2060 
2061 //
2062 //  ============ Main Entry Point ===========
2063 //
2064 GenerateOopMap::GenerateOopMap(const methodHandle& method) {
2065   // We have to initialize all variables here, that can be queried directly
2066   _method = method;
2067   _max_locals=0;
2068   _init_vars = nullptr;
2069 
2070 #ifndef PRODUCT
2071   // If we are doing a detailed trace, include the regular trace information.
2072   if (TraceNewOopMapGenerationDetailed) {
2073     TraceNewOopMapGeneration = true;
2074   }
2075 #endif
2076 }
2077 
2078 bool GenerateOopMap::compute_map(Thread* current) {
2079 #ifndef PRODUCT
2080   if (TimeOopMap2) {
2081     method()->print_short_name(tty);
2082     tty->print("  ");
2083   }
2084   if (TimeOopMap) {
2085     _total_byte_count += method()->code_size();
2086   }
2087 #endif
2088   TraceTime t_single("oopmap time", TimeOopMap2);
2089   TraceTime t_all(nullptr, &_total_oopmap_time, TimeOopMap);
2090 
2091   // Initialize values
2092   _got_error      = false;
2093   _conflict       = false;
2094   _max_locals     = method()->max_locals();
2095   _max_stack      = method()->max_stack();
2096   _has_exceptions = (method()->has_exception_handler());
2097   _nof_refval_conflicts = 0;
2098   _init_vars      = new GrowableArray<intptr_t>(5);  // There are seldom more than 5 init_vars
2099   _report_result  = false;
2100   _report_result_for_send = false;
2101   _new_var_map    = nullptr;
2102   _ret_adr_tos    = new GrowableArray<int>(5);  // 5 seems like a good number;
2103   _did_rewriting  = false;
2104   _did_relocation = false;
2105 
2106   if (TraceNewOopMapGeneration) {
2107     tty->print("Method name: %s\n", method()->name()->as_C_string());
2108     if (Verbose) {
2109       _method->print_codes();
2110       tty->print_cr("Exception table:");
2111       ExceptionTable excps(method());
2112       for(int i = 0; i < excps.length(); i ++) {
2113         tty->print_cr("[%d - %d] -> %d",
2114                       excps.start_pc(i), excps.end_pc(i), excps.handler_pc(i));
2115       }
2116     }
2117   }
2118 
2119   // if no code - do nothing
2120   // compiler needs info
2121   if (method()->code_size() == 0 || _max_locals + method()->max_stack() == 0) {
2122     return true;
2123   }
2124   // Step 1: Compute all jump targets and their return value
2125   if (!_got_error)
2126     _rt.compute_ret_table(_method);
2127 
2128   // Step 2: Find all basic blocks and count GC points
2129   if (!_got_error)
2130     mark_bbheaders();
2131 
2132   // Step 3: Calculate stack maps
2133   if (!_got_error)
2134     do_interpretation();
2135 
2136   // Step 4:Return results
2137   if (!_got_error && report_results())
2138      report_result();
2139 
2140   return !_got_error;
2141 }
2142 
2143 // Error handling methods
2144 //
2145 // If we compute from a suitable JavaThread then we create an exception for the GenerateOopMap
2146 // calling code to retrieve (via exception()) and throw if desired (in most cases errors are ignored).
2147 // Otherwise it is considered a fatal error to hit malformed bytecode.
2148 void GenerateOopMap::error_work(const char *format, va_list ap) {
2149   _got_error = true;
2150   char msg_buffer[512];
2151   (void) os::vsnprintf(msg_buffer, sizeof(msg_buffer), format, ap);
2152   // Append method name
2153   char msg_buffer2[512];
2154   (void) os::snprintf(msg_buffer2, sizeof(msg_buffer2), "%s in method %s", msg_buffer, method()->name()->as_C_string());
2155   Thread* current = Thread::current();
2156   if (current->can_call_java()) {
2157     _exception = Exceptions::new_exception(JavaThread::cast(current),
2158                                            vmSymbols::java_lang_LinkageError(),
2159                                            msg_buffer2);
2160   } else {
2161     fatal("%s", msg_buffer2);
2162   }
2163 }
2164 
2165 void GenerateOopMap::report_error(const char *format, ...) {
2166   va_list ap;
2167   va_start(ap, format);
2168   error_work(format, ap);
2169 }
2170 
2171 void GenerateOopMap::verify_error(const char *format, ...) {
2172   // We do not distinguish between different types of errors for verification
2173   // errors.  Let the verifier give a better message.
2174   report_error("Illegal class file encountered. Try running with -Xverify:all");
2175 }
2176 
2177 //
2178 // Report result opcodes
2179 //
2180 void GenerateOopMap::report_result() {
2181 
2182   if (TraceNewOopMapGeneration) tty->print_cr("Report result pass");
2183 
2184   // We now want to report the result of the parse
2185   _report_result = true;
2186 
2187    // Mark everything changed, then do one interpretation pass.
2188   for (int i = 0; i<_bb_count; i++) {
2189     if (_basic_blocks[i].is_reachable()) {
2190       _basic_blocks[i].set_changed(true);
2191       interp_bb(&_basic_blocks[i]);
2192     }
2193   }
2194 
2195   _report_result = false;
2196 }
2197 
2198 void GenerateOopMap::result_for_basicblock(int bci) {
2199  if (TraceNewOopMapGeneration) tty->print_cr("Report result pass for basicblock");
2200 
2201   // We now want to report the result of the parse
2202   _report_result = true;
2203 
2204   // Find basicblock and report results
2205   BasicBlock* bb = get_basic_block_containing(bci);
2206   guarantee(bb != nullptr, "no basic block for bci");
2207   assert(bb->is_reachable(), "getting result from unreachable basicblock");
2208   bb->set_changed(true);
2209   interp_bb(bb);
2210 }
2211 
2212 //
2213 // Conflict handling code
2214 //
2215 
2216 void GenerateOopMap::record_refval_conflict(int varNo) {
2217   assert(varNo>=0 && varNo< _max_locals, "index out of range");
2218 
2219   if (TraceOopMapRewrites) {
2220      tty->print("### Conflict detected (local no: %d)\n", varNo);
2221   }
2222 
2223   if (!_new_var_map) {
2224     _new_var_map = NEW_RESOURCE_ARRAY(int, _max_locals);
2225     for (int k = 0; k < _max_locals; k++)  _new_var_map[k] = k;
2226   }
2227 
2228   if ( _new_var_map[varNo] == varNo) {
2229     // Check if max. number of locals has been reached
2230     if (_max_locals + _nof_refval_conflicts >= MAX_LOCAL_VARS) {
2231       report_error("Rewriting exceeded local variable limit");
2232       return;
2233     }
2234     _new_var_map[varNo] = _max_locals + _nof_refval_conflicts;
2235     _nof_refval_conflicts++;
2236   }
2237 }
2238 
2239 void GenerateOopMap::rewrite_refval_conflicts()
2240 {
2241   // We can get here two ways: Either a rewrite conflict was detected, or
2242   // an uninitialize reference was detected. In the second case, we do not
2243   // do any rewriting, we just want to recompute the reference set with the
2244   // new information
2245 
2246   int nof_conflicts = 0;              // Used for debugging only
2247 
2248   if ( _nof_refval_conflicts == 0 )
2249      return;
2250 
2251   // Check if rewrites are allowed in this parse.
2252   if (!allow_rewrites()) {
2253     fatal("Rewriting method not allowed at this stage");
2254   }
2255 
2256 
2257   // Tracing flag
2258   _did_rewriting = true;
2259 
2260   if (TraceOopMapRewrites) {
2261     tty->print_cr("ref/value conflict for method %s - bytecodes are getting rewritten", method()->name()->as_C_string());
2262     method()->print();
2263     method()->print_codes();
2264   }
2265 
2266   assert(_new_var_map!=nullptr, "nothing to rewrite");
2267   assert(_conflict==true, "We should not be here");
2268 
2269   compute_ret_adr_at_TOS();
2270   if (!_got_error) {
2271     for (int k = 0; k < _max_locals && !_got_error; k++) {
2272       if (_new_var_map[k] != k) {
2273         if (TraceOopMapRewrites) {
2274           tty->print_cr("Rewriting: %d -> %d", k, _new_var_map[k]);
2275         }
2276         rewrite_refval_conflict(k, _new_var_map[k]);
2277         if (_got_error) return;
2278         nof_conflicts++;
2279       }
2280     }
2281   }
2282 
2283   assert(nof_conflicts == _nof_refval_conflicts, "sanity check");
2284 
2285   // Adjust the number of locals
2286   method()->set_max_locals(_max_locals+_nof_refval_conflicts);
2287   _max_locals += _nof_refval_conflicts;
2288 
2289   // That was that...
2290   _new_var_map = nullptr;
2291   _nof_refval_conflicts = 0;
2292 }
2293 
2294 void GenerateOopMap::rewrite_refval_conflict(int from, int to) {
2295   bool startOver;
2296   do {
2297     // Make sure that the BytecodeStream is constructed in the loop, since
2298     // during rewriting a new method is going to be used, and the next time
2299     // around we want to use that.
2300     BytecodeStream bcs(_method);
2301     startOver = false;
2302 
2303     while( !startOver && !_got_error &&
2304            // test bcs in case method changed and it became invalid
2305            bcs.next() >=0) {
2306       startOver = rewrite_refval_conflict_inst(&bcs, from, to);
2307     }
2308   } while (startOver && !_got_error);
2309 }
2310 
2311 /* If the current instruction is one that uses local variable "from"
2312    in a ref way, change it to use "to". There's a subtle reason why we
2313    renumber the ref uses and not the non-ref uses: non-ref uses may be
2314    2 slots wide (double, long) which would necessitate keeping track of
2315    whether we should add one or two variables to the method. If the change
2316    affected the width of some instruction, returns "TRUE"; otherwise, returns "FALSE".
2317    Another reason for moving ref's value is for solving (addr, ref) conflicts, which
2318    both uses aload/astore methods.
2319 */
2320 bool GenerateOopMap::rewrite_refval_conflict_inst(BytecodeStream *itr, int from, int to) {
2321   Bytecodes::Code bc = itr->code();
2322   int index;
2323   int bci = itr->bci();
2324 
2325   if (is_aload(itr, &index) && index == from) {
2326     if (TraceOopMapRewrites) {
2327       tty->print_cr("Rewriting aload at bci: %d", bci);
2328     }
2329     return rewrite_load_or_store(itr, Bytecodes::_aload, Bytecodes::_aload_0, to);
2330   }
2331 
2332   if (is_astore(itr, &index) && index == from) {
2333     if (!stack_top_holds_ret_addr(bci)) {
2334       if (TraceOopMapRewrites) {
2335         tty->print_cr("Rewriting astore at bci: %d", bci);
2336       }
2337       return rewrite_load_or_store(itr, Bytecodes::_astore, Bytecodes::_astore_0, to);
2338     } else {
2339       if (TraceOopMapRewrites) {
2340         tty->print_cr("Suppress rewriting of astore at bci: %d", bci);
2341       }
2342     }
2343   }
2344 
2345   return false;
2346 }
2347 
2348 // The argument to this method is:
2349 // bc : Current bytecode
2350 // bcN : either _aload or _astore
2351 // bc0 : either _aload_0 or _astore_0
2352 bool GenerateOopMap::rewrite_load_or_store(BytecodeStream *bcs, Bytecodes::Code bcN, Bytecodes::Code bc0, unsigned int varNo) {
2353   assert(bcN == Bytecodes::_astore   || bcN == Bytecodes::_aload,   "wrong argument (bcN)");
2354   assert(bc0 == Bytecodes::_astore_0 || bc0 == Bytecodes::_aload_0, "wrong argument (bc0)");
2355   int ilen = Bytecodes::length_at(_method(), bcs->bcp());
2356   int newIlen;
2357 
2358   if (ilen == 4) {
2359     // Original instruction was wide; keep it wide for simplicity
2360     newIlen = 4;
2361   } else if (varNo < 4)
2362      newIlen = 1;
2363   else if (varNo >= 256)
2364      newIlen = 4;
2365   else
2366      newIlen = 2;
2367 
2368   // If we need to relocate in order to patch the byte, we
2369   // do the patching in a temp. buffer, that is passed to the reloc.
2370   // The patching of the bytecode stream is then done by the Relocator.
2371   // This is necessary, since relocating the instruction at a certain bci, might
2372   // also relocate that instruction, e.g., if a _goto before it gets widen to a _goto_w.
2373   // Hence, we do not know which bci to patch after relocation.
2374 
2375   assert(newIlen <= 4, "sanity check");
2376   u_char inst_buffer[4]; // Max. instruction size is 4.
2377   address bcp;
2378 
2379   if (newIlen != ilen) {
2380     // Relocation needed do patching in temp. buffer
2381     bcp = (address)inst_buffer;
2382   } else {
2383     bcp = _method->bcp_from(bcs->bci());
2384   }
2385 
2386   // Patch either directly in Method* or in temp. buffer
2387   if (newIlen == 1) {
2388     assert(varNo < 4, "varNo too large");
2389     *bcp = (u1)(bc0 + varNo);
2390   } else if (newIlen == 2) {
2391     assert(varNo < 256, "2-byte index needed!");
2392     *(bcp + 0) = bcN;
2393     *(bcp + 1) = (u1)varNo;
2394   } else {
2395     assert(newIlen == 4, "Wrong instruction length");
2396     *(bcp + 0) = Bytecodes::_wide;
2397     *(bcp + 1) = bcN;
2398     Bytes::put_Java_u2(bcp+2, (u2)varNo);
2399   }
2400 
2401   if (newIlen != ilen) {
2402     expand_current_instr(bcs->bci(), ilen, newIlen, inst_buffer);
2403   }
2404 
2405 
2406   return (newIlen != ilen);
2407 }
2408 
2409 class RelocCallback : public RelocatorListener {
2410  private:
2411   GenerateOopMap* _gom;
2412  public:
2413    RelocCallback(GenerateOopMap* gom) { _gom = gom; };
2414 
2415   // Callback method
2416   virtual void relocated(int bci, int delta, int new_code_length) {
2417     _gom->update_basic_blocks  (bci, delta, new_code_length);
2418     _gom->update_ret_adr_at_TOS(bci, delta);
2419     _gom->_rt.update_ret_table (bci, delta);
2420   }
2421 };
2422 
2423 // Returns true if expanding was successful. Otherwise, reports an error and
2424 // returns false.
2425 void GenerateOopMap::expand_current_instr(int bci, int ilen, int newIlen, u_char inst_buffer[]) {
2426   JavaThread* THREAD = JavaThread::current(); // For exception macros.
2427   RelocCallback rcb(this);
2428   Relocator rc(_method, &rcb);
2429   methodHandle m= rc.insert_space_at(bci, newIlen, inst_buffer, THREAD);
2430   if (m.is_null() || HAS_PENDING_EXCEPTION) {
2431     report_error("could not rewrite method - exception occurred or bytecode buffer overflow");
2432     return;
2433   }
2434 
2435   // Relocator returns a new method.
2436   _did_relocation = true;
2437   _method = m;
2438 }
2439 
2440 
2441 bool GenerateOopMap::is_astore(BytecodeStream *itr, int *index) {
2442   Bytecodes::Code bc = itr->code();
2443   switch(bc) {
2444     case Bytecodes::_astore_0:
2445     case Bytecodes::_astore_1:
2446     case Bytecodes::_astore_2:
2447     case Bytecodes::_astore_3:
2448       *index = bc - Bytecodes::_astore_0;
2449       return true;
2450     case Bytecodes::_astore:
2451       *index = itr->get_index();
2452       return true;
2453     default:
2454       return false;
2455   }
2456 }
2457 
2458 bool GenerateOopMap::is_aload(BytecodeStream *itr, int *index) {
2459   Bytecodes::Code bc = itr->code();
2460   switch(bc) {
2461     case Bytecodes::_aload_0:
2462     case Bytecodes::_aload_1:
2463     case Bytecodes::_aload_2:
2464     case Bytecodes::_aload_3:
2465       *index = bc - Bytecodes::_aload_0;
2466       return true;
2467 
2468     case Bytecodes::_aload:
2469       *index = itr->get_index();
2470       return true;
2471 
2472     default:
2473       return false;
2474   }
2475 }
2476 
2477 
2478 // Return true iff the top of the operand stack holds a return address at
2479 // the current instruction
2480 bool GenerateOopMap::stack_top_holds_ret_addr(int bci) {
2481   for(int i = 0; i < _ret_adr_tos->length(); i++) {
2482     if (_ret_adr_tos->at(i) == bci)
2483       return true;
2484   }
2485 
2486   return false;
2487 }
2488 
2489 void GenerateOopMap::compute_ret_adr_at_TOS() {
2490   assert(_ret_adr_tos != nullptr, "must be initialized");
2491   _ret_adr_tos->clear();
2492 
2493   for (int i = 0; i < bb_count(); i++) {
2494     BasicBlock* bb = &_basic_blocks[i];
2495 
2496     // Make sure to only check basicblocks that are reachable
2497     if (bb->is_reachable()) {
2498 
2499       // For each Basic block we check all instructions
2500       BytecodeStream bcs(_method);
2501       bcs.set_interval(bb->_bci, next_bb_start_pc(bb));
2502 
2503       restore_state(bb);
2504 
2505       while (bcs.next()>=0 && !_got_error) {
2506         // TDT: should this be is_good_address() ?
2507         if (_stack_top > 0 && stack()[_stack_top-1].is_address()) {
2508           _ret_adr_tos->append(bcs.bci());
2509           if (TraceNewOopMapGeneration) {
2510             tty->print_cr("Ret_adr TOS at bci: %d", bcs.bci());
2511           }
2512         }
2513         interp1(&bcs);
2514       }
2515     }
2516   }
2517 }
2518 
2519 void GenerateOopMap::update_ret_adr_at_TOS(int bci, int delta) {
2520   for(int i = 0; i < _ret_adr_tos->length(); i++) {
2521     int v = _ret_adr_tos->at(i);
2522     if (v > bci)  _ret_adr_tos->at_put(i, v + delta);
2523   }
2524 }
2525 
2526 // ===================================================================
2527 
2528 #ifndef PRODUCT
2529 int ResolveOopMapConflicts::_nof_invocations  = 0;
2530 int ResolveOopMapConflicts::_nof_rewrites     = 0;
2531 int ResolveOopMapConflicts::_nof_relocations  = 0;
2532 #endif
2533 
2534 methodHandle ResolveOopMapConflicts::do_potential_rewrite(TRAPS) {
2535   if (!compute_map(THREAD)) {
2536     THROW_HANDLE_(exception(), methodHandle());
2537   }
2538 
2539 #ifndef PRODUCT
2540   // Tracking and statistics
2541   if (PrintRewrites) {
2542     _nof_invocations++;
2543     if (did_rewriting()) {
2544       _nof_rewrites++;
2545       if (did_relocation()) _nof_relocations++;
2546       tty->print("Method was rewritten %s: ", (did_relocation()) ? "and relocated" : "");
2547       method()->print_value(); tty->cr();
2548       tty->print_cr("Cand.: %d rewrts: %d (%d%%) reloc.: %d (%d%%)",
2549           _nof_invocations,
2550           _nof_rewrites,    (_nof_rewrites    * 100) / _nof_invocations,
2551           _nof_relocations, (_nof_relocations * 100) / _nof_invocations);
2552     }
2553   }
2554 #endif
2555   return methodHandle(THREAD, method());
2556 }