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