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