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