rev 13014 : imported patch 8180755-remove-bitmap-inline-hpp-include

   1 /*
   2  * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "interpreter/bytecodeStream.hpp"
  27 #include "logging/log.hpp"
  28 #include "oops/generateOopMap.hpp"
  29 #include "oops/oop.inline.hpp"
  30 #include "oops/symbol.hpp"
  31 #include "prims/methodHandles.hpp"
  32 #include "runtime/handles.inline.hpp"
  33 #include "runtime/java.hpp"
  34 #include "runtime/relocator.hpp"
  35 #include "runtime/timerTrace.hpp"
  36 #include "utilities/bitMap.inline.hpp"
  37 #include "utilities/ostream.hpp"

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