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